Compare commits

..

17 Commits

Author SHA1 Message Date
Hans Mackowiak
25b6db1536 fix unused variables 2021-03-25 09:32:20 +01:00
Hans Mackowiak
245586cefa GameAction: removeExiledWith when zone is not exile 2021-03-25 09:32:20 +01:00
Hans Mackowiak
21999488f4 fix usage of CardLists getValidCards using CardTraitBase if able 2021-03-25 09:32:20 +01:00
Hans Mackowiak
d8b9524f80 Card: ChosenType linked to CTB 2021-03-25 09:32:20 +01:00
Hans Mackowiak
3bda4ffe0a AI: fix moved Devotion xcount 2021-03-25 09:32:20 +01:00
Hans Mackowiak
4dba174a6c Card: chosenColors use Table for LinkedAbilities 2021-03-25 09:32:20 +01:00
Hans Mackowiak
f57f6e1c40 fix skyclave apparition and spell queller exiling multiple cards 2021-03-25 09:32:20 +01:00
Hans Mackowiak
c9c974ad00 ExiledWithTable: add way to exile without CardTraitBase for GameState 2021-03-25 09:32:20 +01:00
Hans Mackowiak
18be2c67b6 CardTraitBase: add matchesValidParam and use for Trigger 2021-03-25 09:32:20 +01:00
Michael Kamensky
c27fa18ed7 - Unbreak some AI logic parts 2021-03-25 09:32:20 +01:00
Michael Kamensky
fb7a212597 - Port over the AI logic for Ashiok 2021-03-25 09:32:20 +01:00
Hans Mackowiak
c05f2396a1 Hideaway: fix keyword using ExiledWith 2021-03-25 09:32:20 +01:00
Hans Mackowiak
0ac7fb59e6 CardTraitBase: matchesValid as instance method, better use for isValid 2021-03-25 09:32:20 +01:00
Hans Mackowiak
1db6a772ed cards: update more cards with Remember and ExiledWith 2021-03-25 09:32:20 +01:00
Michael Kamensky
d12527ff21 - Update PC_041415 to work with the changed card script. 2021-03-25 09:32:20 +01:00
Hans Mackowiak
ab5eb24d7a Fix ixalans_binding using Static+ExiledWith 2021-03-25 09:32:20 +01:00
Hans Mackowiak
9f5fd3f35f ExiledWithTable to reduce the need for Remember 2021-03-25 09:32:20 +01:00
42751 changed files with 459213 additions and 1302556 deletions

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"

19
.gitignore vendored
View File

@@ -12,21 +12,17 @@
.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
@@ -36,11 +32,6 @@ bin
gen
*.log
# Ignore macOS Spotlight rubbish
.DS_Store
# ignore vim swapfiles
*.swp
# TODO: specify what these ignores are for (releasing?)
@@ -66,9 +57,6 @@ forge-gui-mobile-dev/testAssets
forge-gui/res/cardsfolder/*.bat
# Generated changelog file
forge-gui/release-files/CHANGES.txt
forge-gui/res/PerSetTrackingResults
forge-gui/res/decks
forge-gui/res/layouts
@@ -87,10 +75,3 @@ 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

View File

@@ -0,0 +1,33 @@
Summary
(Summarize the bug encountered concisely)
Steps to reproduce
(How one can reproduce the issue - this is very important. Specific cards and specific actions especially)
Which version of Forge are you on (Release, Snapshot? Desktop, Android?)
What is the current bug behavior?
(What actually happens)
What is the expected correct behavior?
(What you should see instead)
Relevant logs and/or screenshots
(Paste/Attach your game.log from the crash - please use code blocks (```)) Also, provide screenshots of the current state.
Possible fixes
(If you can, link to the line of code that might be responsible for the problem)
/label ~needs-investigation

View File

@@ -0,0 +1,15 @@
Summary
(Summarize the feature you wish concisely)
Example screenshots
(If this is a UI change, please provide an example screenshot of how this feature might work)
Feature type
(Where in Forge does this belong? e.g. Quest Mode, Deck Editor, Limited, Constructed, etc.)
/label ~feature request

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

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.

263
README.md
View File

@@ -1,105 +1,230 @@
# ⚔️ Forge: The Magic: The Gathering Rules Engine
# Forge
Join the **Forge community** on [Discord](https://discord.gg/HcPJNyD66a)!
Gitlab repo is found [here](https://git.cardforge.org/core-developers/forge).
[![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)
Dev instructions here: [Getting Started](https://www.slightlymagic.net/wiki/Forge:How_to_Get_Started_Developing_Forge) (Somewhat outdated)
---
Discord channel [here](https://discordapp.com/channels/267367946135928833/267742313390931968)
## ✨ Introduction
# Requirements / Tools
**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.
- Java IDE such as IntelliJ or Eclipse
- Java JDK 8 or later
- Git
- Git client (optional)
- Maven
- Gitlab 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)
**Note:** Forge operates independently and is not affiliated with Wizards of the Coast.
# Project Quick Setup
---
- Log in to gitlab with your user account and fork the project.
## 🌟 Key Features
- Clone your forked project to your local machine
- **🌐 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!
- 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`
---
# Eclipse
## 🛠️ Installation Guide
Eclipse includes Maven integration so a separate install is not necessary. For other IDEs, your mileage may vary.
### 📥 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.
## Project Setup
### 📱 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.
- Follow the instructions for cloning from Gitlab. You'll need a Gitlab account setup and an SSH key defined.
---
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 Gitlab profile under
"SSH keys". Run pageant.exe and add the private key generated earlier. TortoiseGit will use this for accessing Gitlab.
## 🎮 Modes of Play
- Fork the Forge git repo to your Gitlab account.
Forge offers various exciting gameplay options:
- Clone your forked repo to your local machine.
### 🌍 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.
- Make sure the Java SDK is installed -- not just the JRE. Java 8 or newer required. If you execute `java -version` at the shell or command prompt, it should report version 1.8 or later.
<img width="1282" height="752" alt="Shandalar World" src="https://github.com/user-attachments/assets/9af31471-d688-442f-9418-9807d8635b72" />
- Install Eclipse 2018-12 or later for Java. Launch it.
### 🔍 Quest Modes
Engage in focused gameplay without the overworld exploration—perfect for quick sessions!
- 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.
<img width="1282" height="752" alt="Quest Duels" src="https://github.com/user-attachments/assets/b9613b1c-e8c3-4320-8044-6922c519aad4" />
- 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.
### 🤖 AI Formats
Test your skills against AI in multiple formats:
- **Sealed**
- **Draft**
- **Commander**
- **Cube**
- Once everything builds, all errors should disappear. You can now advance to Project launch.
For comprehensive gameplay instructions, visit our [Gameplay Guide](https://github.com/Card-Forge/forge/wiki/Gameplay-Guide).
## Project Launch
<img width="1282" height="752" alt="Sealed" src="https://github.com/user-attachments/assets/ae603dbd-4421-4753-a333-87cb0a28d772" />
### Desktop
---
This is the standard configuration used for releasing to Windows / Linux / MacOS.
## 💬 Support & Community
- Right-click on forge-gui-desktop > Run As... > Java Application > "Main - forge.view" > Ok
Need help? Join our vibrant Discord community!
- 📜 Read the **#rules** and explore the **FAQ**.
- ❓ Ask your questions in the **#help** channel for assistance.
- The familiar Forge splash screen, etc. should appear. Enjoy!
---
### Mobile (Desktop dev)
## 🤝 Contributing to Forge
This is the configuration used for doing mobile development using the Windows / Linux / MacOS front-end. Knowledge of libgdx is helpful here.
We love community contributions! Interested in helping? Check out our [Contributing Guidelines](CONTRIBUTING.md) for details on how to get started.
- 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!
## About Forge
## Eclipse / Android SDK Integration
Forge aims to deliver an immersive and customizable Magic: The Gathering experience for fans around the world.
Google no longer supports Android SDK releases for Eclipse. That said, it is still possible to build and debug Android platforms.
### 📊 Repository Statistics
### Android SDK
| 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) |
Reference SO for obtaining a specific release: https://stackoverflow.com/questions/27043522/where-can-i-download-an-older-version-of-the-android-sdk
---
#### Windows
Download the following archived version of the Android SDK: http://dl-ssl.google.com/android/repository/tools_r25.2.3-windows.zip. Install it somewhere on your machine. This is referenced
in the following instructions as your 'Android SDK Install' path.
#### Linux / Mac OSX
TBD
### Android Plugin for Eclipse
Google's last plugin release does not work completely with target's running Android 7.0 or later. Download the ADT-24.2.0-20160729.zip plugin
from: https://github.com/khaledev/ADT/releases
In Eclipse go to: Help > Install New Software... > Add > Name: ADT Update, Click on the "Archive:" button and navigate to the downloaded ADT-24.2.0-20160729.zip file > Add. Install all "Developer Tools". Eclipse
should restart and prompt you to run the SDK Manager. Launch it and continue to the next steps below.
### Android Platform
In Eclipse, if the SDK Manager is not already running, go to Window > Android SDK Manager. Install the following options / versions:
- Android SDK Build-tools 26.0.1
- Android 7.1.1 (API 25) SDK Platform
- Google USB Driver 11
Note that this will populate additional tools in the Android SDK install path extracted above.
### Proguard update
The Proguard included with the Android SDK Build-tools is outdated and does not work with Java 1.8. Download Proguard 6.0.3 from https://sourceforge.net/projects/proguard/files/proguard/6.0/.
- Go to the Android SDK install path. Rename the tools/proguard/ path to tools/proguard4.7/.
- Extract Proguard 6.0.3 to the Android SDK install path under tools/. You will need to rename the dir proguard6.0.3/ to proguard/.
### Android Build
The Eclipse plug-ins do NOT support building things for Android. They do however allow you to use the debugger so you can still set breakpoints and trace
things out. The steps below show how to generate a debug Android build.
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
2) Run forge Maven build. If everything built, you should see "BUILD SUCCESS" in the Console View.
3) Right-click on the forge-gui-android project. Run as.. > Maven build...
- On the Main tab, set Goals: install, Profiles: android-debug
- On the Environment tab, you may need to define the variable ANDROID_HOME with the value containing the path to your Android SDK installation. For example, Variable: ANDROID_HOME, Value: Your Android SDK install path here.
4) Run the forge-gui-android Maven build. This may take a few minutes. If everything worked, you should see "BUILD SUCCESS" in the Console View.
Assuming you got this far, you should have an Android forge-android-[version].apk in the forge-gui-android/target path.
### Android Deploy
You'll need to have the Android SDK install path platform-tools/ path in your command search path to easily deploy builds.
- Open a command prompt. Navigate to the forge-gui-android/target/ path.
- Connect your Android device to your dev machine.
- Ensure the device is visible using `adb devices`
- Remove the old Forge install if present: `adb uninstall forge.app`
- Install the new apk: `adb install forge-android-[version].apk`
### Android Debugging
Assuming the apk is installed, launch it from the device.
In Eclipse, launch the DDMS. Window > Perspective > Open Perspective > Other... > DDMS. You should see the forge app in the list. Highlight the app, click on the green debug button and a
green debug button should appear next to the app's name. You can now set breakpoints and step through the source code.
## 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
# IntelliJ
Quick start guide for [setting up the Forge project within IntelliJ](https://git.cardforge.org/core-developers/forge/wikis/intellij-setup).
# Card Scripting
Visit [this page](https://www.slightlymagic.net/wiki/Forge_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
### forge-core
### forge-game
### forge-gui
The forge-gui project includes 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.
**📄 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);
}
}
}
}

View File

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

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,17 +18,13 @@
package forge.ai;
import java.util.Map;
import java.util.HashSet;
import java.util.Iterator;
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;
/**
* <p>
* AiCardMemory class.
@@ -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 && memorySet.contains(c);
}
/**
@@ -99,7 +149,20 @@ 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);
if (memorySet != null) {
Iterator<Card> it = memorySet.iterator();
while (it.hasNext()) {
Card c = it.next();
if (c.getName().equals(cardName)) {
return true;
}
}
}
return false;
}
/**
@@ -113,7 +176,20 @@ 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);
if (memorySet != null) {
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 +202,14 @@ public class AiCardMemory {
public boolean rememberCard(Card c, MemorySet set) {
if (c == null)
return false;
return getMemorySet(set).add(c);
Set<Card> memorySet = getMemorySet(set);
if (memorySet != null) {
memorySet.add(c);
}
return true;
}
/**
@@ -143,7 +226,14 @@ public class AiCardMemory {
if (!isRememberedCard(c, set)) {
return false;
}
return getMemorySet(set).remove(c);
Set<Card> memorySet = getMemorySet(set);
if (memorySet != null) {
memorySet.remove(c);
}
return true;
}
/**
@@ -154,11 +244,19 @@ 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);
if (memorySet != null) {
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 +269,19 @@ 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);
if (memorySet != null) {
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;
}
@@ -207,12 +313,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;

File diff suppressed because it is too large Load Diff

View File

@@ -1,82 +1,106 @@
package forge.ai;
import static forge.ai.ComputerUtilCard.getBestCreatureAI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import forge.ai.AiCardMemory.MemorySet;
import forge.card.CardType;
import forge.card.MagicColor;
import forge.game.Game;
import forge.game.GameEntityCounterTable;
import forge.game.ability.AbilityUtils;
import forge.game.card.*;
import forge.game.cost.*;
import forge.game.card.Card;
import forge.game.card.CardCollection;
import forge.game.card.CardCollectionView;
import forge.game.card.CardLists;
import forge.game.card.CardPredicates;
import forge.game.card.CounterEnumType;
import forge.game.card.CounterType;
import forge.game.cost.CostAddMana;
import forge.game.cost.CostChooseCreatureType;
import forge.game.cost.CostDamage;
import forge.game.cost.CostDecisionMakerBase;
import forge.game.cost.CostDiscard;
import forge.game.cost.CostDraw;
import forge.game.cost.CostExert;
import forge.game.cost.CostExile;
import forge.game.cost.CostExileFromStack;
import forge.game.cost.CostExiledMoveToGrave;
import forge.game.cost.CostFlipCoin;
import forge.game.cost.CostGainControl;
import forge.game.cost.CostGainLife;
import forge.game.cost.CostMill;
import forge.game.cost.CostPartMana;
import forge.game.cost.CostPayEnergy;
import forge.game.cost.CostPayLife;
import forge.game.cost.CostPutCardToLib;
import forge.game.cost.CostPutCounter;
import forge.game.cost.CostRemoveAnyCounter;
import forge.game.cost.CostRemoveCounter;
import forge.game.cost.CostReturn;
import forge.game.cost.CostReveal;
import forge.game.cost.CostSacrifice;
import forge.game.cost.CostTap;
import forge.game.cost.CostTapType;
import forge.game.cost.CostUnattach;
import forge.game.cost.CostUntap;
import forge.game.cost.CostUntapType;
import forge.game.cost.PaymentDecision;
import forge.game.keyword.Keyword;
import forge.game.player.Player;
import forge.game.spellability.SpellAbility;
import forge.game.spellability.SpellAbilityStackInstance;
import forge.game.zone.ZoneType;
import forge.util.Aggregates;
import forge.util.Localizer;
import forge.util.TextUtil;
import forge.util.collect.FCollectionView;
import org.apache.commons.lang3.ObjectUtils;
import java.util.*;
import static forge.ai.ComputerUtilCard.getBestCreatureAI;
public class AiCostDecision extends CostDecisionMakerBase {
private final SpellAbility ability;
private final Card source;
private final CardCollection discarded;
private final CardCollection tapped;
public AiCostDecision(Player ai0, SpellAbility sa, final boolean effect) {
this(ai0, sa, effect, false);
}
public AiCostDecision(Player ai0, SpellAbility sa, final boolean effect, final boolean payMana) {
super(ai0, effect, sa, sa.getHostCard());
public AiCostDecision(Player ai0, SpellAbility sa) {
super(ai0);
ability = sa;
source = ability.getHostCard();
discarded = new CardCollection();
tapped = new CardCollection();
Set<Card> tappedForMana = AiCardMemory.getMemorySet(ai0, MemorySet.PAYS_TAP_COST);
if (!payMana && tappedForMana != null) {
tapped.addAll(tappedForMana);
}
}
@Override
public PaymentDecision visit(CostAddMana cost) {
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostBehold cost) {
final String type = cost.getType();
CardCollectionView hand = player.getCardsIn(cost.getRevealFrom());
hand = CardLists.getValidCards(hand, type.split(";"), player, source, ability);
return hand.isEmpty() ? null : PaymentDecision.card(getBestCreatureAI(hand));
}
@Override
public PaymentDecision visit(CostChooseColor cost) {
int c = cost.getAbilityAmount(ability);
List<String> choices = player.getController().chooseColors("Color", ability, c, c,
new ArrayList<>(MagicColor.Constant.ONLY_COLORS));
return PaymentDecision.colors(choices);
}
@Override
public PaymentDecision visit(CostChooseCreatureType cost) {
String choice = player.getController().chooseSomeType("Creature", ability, CardType.getAllCreatureTypes());
return PaymentDecision.type(choice);
Integer amount = cost.convertAmount();
Iterable<String> choices = player.getController().chooseSomeType(
Localizer.getInstance().getMessage("lblCreature"), ability, amount, amount, Lists.newArrayList(CardType.getAllCreatureTypes()));
if (choices == null || Iterables.isEmpty(choices)) {
return null;
}
@Override
public PaymentDecision visit(CostCollectEvidence cost) {
int c = cost.getAbilityAmount(ability);
CardCollectionView chosen = ComputerUtil.chooseCollectEvidence(player, cost, source, c, ability, isEffect());
return null == chosen ? null : PaymentDecision.card(chosen);
return PaymentDecision.types(choices);
}
@Override
@@ -89,13 +113,15 @@ public class AiCostDecision extends CostDecisionMakerBase {
return null;
}
return PaymentDecision.card(player.getLastDrawnCard());
} else if (cost.payCostFromSource()) {
}
else if (cost.payCostFromSource()) {
if (!hand.contains(source)) {
return null;
}
return PaymentDecision.card(source);
} else if (type.equals("Hand")) {
}
else if (type.equals("Hand")) {
if (hand.size() > 1 && ability.getActivatingPlayer() != null) {
hand = ability.getActivatingPlayer().getController().orderMoveToZoneList(hand, ZoneType.Graveyard, ability);
}
@@ -105,7 +131,10 @@ public class AiCostDecision extends CostDecisionMakerBase {
if (type.contains("WithSameName")) {
return null;
}
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
if (type.equals("Random")) {
CardCollectionView randomSubset = CardLists.getRandomSubList(new CardCollection(hand), c);
@@ -113,24 +142,26 @@ public class AiCostDecision extends CostDecisionMakerBase {
randomSubset = ability.getActivatingPlayer().getController().orderMoveToZoneList(randomSubset, ZoneType.Graveyard, ability);
}
return PaymentDecision.card(randomSubset);
} else if (type.contains("+WithDifferentNames")) {
}
else if (type.equals("DifferentNames")) {
CardCollection differentNames = new CardCollection();
CardCollection discardMe = CardLists.filter(hand, CardPredicates.hasSVar("DiscardMe"));
while (c > 0) {
Card chosen;
if (!discardMe.isEmpty()) {
chosen = Aggregates.random(discardMe);
discardMe = CardLists.filter(discardMe, CardPredicates.sharesNameWith(chosen).negate());
discardMe = CardLists.filter(discardMe, Predicates.not(CardPredicates.sharesNameWith(chosen)));
} else {
final Card worst = ComputerUtilCard.getWorstAI(hand);
chosen = worst != null ? worst : Aggregates.random(hand);
}
differentNames.add(chosen);
hand = CardLists.filter(hand, CardPredicates.sharesNameWith(chosen).negate());
hand = CardLists.filter(hand, Predicates.not(CardPredicates.sharesNameWith(chosen)));
c--;
}
return PaymentDecision.card(differentNames);
} else {
}
else {
final AiController aic = ((PlayerControllerAi)player.getController()).getAi();
CardCollection result = aic.getCardsToDiscard(c, type.split(";"), ability, discarded);
@@ -143,90 +174,67 @@ public class AiCostDecision extends CostDecisionMakerBase {
@Override
public PaymentDecision visit(CostDamage cost) {
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostDraw cost) {
if (!cost.canPay(ability, player, isEffect())) {
return null;
}
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
List<Player> res = cost.getPotentialPlayers(player, ability);
PaymentDecision decision = PaymentDecision.players(res);
decision.c = c;
return decision;
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
@Override
public PaymentDecision visit(CostPromiseGift cost) {
if (!cost.canPay(ability, player, isEffect())) {
return null;
}
List<Player> res = cost.getPotentialPlayers(player, ability);
// I should only choose one of these right?
// TODO Choose the "worst" player.
Collections.shuffle(res);
return PaymentDecision.players(res.subList(0, 1));
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostExile cost) {
String type = cost.getType();
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
if (type.equals("All")) {
if (cost.getType().equals("All")) {
return PaymentDecision.card(player.getCardsIn(cost.getFrom()));
} else if (type.contains("FromTopGrave")) {
return null;
} else if (type.contains("+withTotalCMCGE")) {
String strAmount = type.split("withTotalCMCGE")[1];
int amount = AbilityUtils.calculateAmount(source, strAmount, ability);
String typeCleaned = TextUtil.fastReplace(type, TextUtil.concatNoSpace("+withTotalCMCGE", strAmount), "");
CardCollection valid = CardLists.getValidCards(player.getGame().getCardsIn(cost.getFrom().get(0)), typeCleaned, player, source, ability);
CardCollection chosen = new CardCollection();
CardLists.sortByCmcDesc(valid);
Collections.reverse(valid);
int totalCMC = 0;
for (Card card : valid) {
totalCMC += card.getCMC();
chosen.add(card);
if (totalCMC >= amount) {
return PaymentDecision.card(chosen);
}
}
else if (cost.getType().contains("FromTopGrave")) {
return null;
}
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
if (cost.from.size() == 1 && cost.getFrom().get(0).equals(ZoneType.Library)) {
if (cost.getFrom().equals(ZoneType.Library)) {
return PaymentDecision.card(player.getCardsIn(ZoneType.Library, c));
}
else if (cost.zoneRestriction == 0) {
else if (cost.sameZone) {
// TODO Determine exile from same zone for AI
return null;
} else {
CardCollectionView chosen = ComputerUtil.chooseExileFrom(player, cost, source, c, ability, isEffect());
}
else {
CardCollectionView chosen = ComputerUtil.chooseExileFrom(player, cost.getFrom(), cost.getType(), source, ability.getTargetCard(), c, ability);
return null == chosen ? null : PaymentDecision.card(chosen);
}
}
@Override
public PaymentDecision visit(CostExileFromStack cost) {
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
List<SpellAbility> chosen = Lists.newArrayList();
for (SpellAbilityStackInstance si :source.getGame().getStack()) {
SpellAbility sp = si.getSpellAbility().getRootAbility();
SpellAbility sp = si.getSpellAbility(true).getRootAbility();
if (si.getSourceCard().isValid(cost.getType().split(";"), source.getController(), source, sp)) {
chosen.add(sp);
}
@@ -236,9 +244,12 @@ public class AiCostDecision extends CostDecisionMakerBase {
@Override
public PaymentDecision visit(CostExiledMoveToGrave cost) {
Integer c = cost.convertAmount();
CardCollection chosen = new CardCollection();
int c = cost.getAbilityAmount(ability);
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Exile), cost.getType().split(";"), player, source, ability);
@@ -246,7 +257,8 @@ public class AiCostDecision extends CostDecisionMakerBase {
return null;
}
CardLists.sortByPowerDesc(typeList);
CardLists.sortByPowerAsc(typeList);
Collections.reverse(typeList);
for (int i = 0; i < c; i++) {
chosen.add(typeList.get(i));
@@ -261,7 +273,10 @@ public class AiCostDecision extends CostDecisionMakerBase {
return PaymentDecision.card(source);
}
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
final CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, source, ability);
@@ -278,36 +293,12 @@ public class AiCostDecision extends CostDecisionMakerBase {
return res.isEmpty() ? null : PaymentDecision.card(res);
}
@Override
public PaymentDecision visit(final CostEnlist cost) {
CardCollection choices = CostEnlist.getCardsForEnlisting(player);
CardLists.sortByPowerDesc(choices);
return choices.isEmpty() ? null : PaymentDecision.card(choices.getFirst());
}
@Override
public PaymentDecision visit(CostFlipCoin cost) {
int c = cost.getAbilityAmount(ability);
return PaymentDecision.number(c);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
@Override
public PaymentDecision visit(final CostForage cost) {
CardCollection food = CardLists.filter(player.getCardsIn(ZoneType.Battlefield), CardPredicates.isType("Food"), CardPredicates.canBeSacrificedBy(ability, isEffect()));
CardCollection exile = CardLists.filter(player.getCardsIn(ZoneType.Graveyard), CardPredicates.canExiledBy(ability, isEffect()));
if (!food.isEmpty()) {
final AiController aic = ((PlayerControllerAi)player.getController()).getAi();
CardCollectionView list = aic.chooseSacrificeType("Food", ability, isEffect(), 1, null);
return list == null ? null : PaymentDecision.card(list);
} else {
CardCollectionView chosen = ComputerUtil.chooseExileFromList(player, exile, source, 3, ability, isEffect());
return null == chosen ? null : PaymentDecision.card(chosen);
}
}
@Override
public PaymentDecision visit(CostRollDice cost) {
int c = cost.getAbilityAmount(ability);
return PaymentDecision.number(c);
}
@@ -317,10 +308,12 @@ public class AiCostDecision extends CostDecisionMakerBase {
return PaymentDecision.card(source);
}
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, source, ability);
typeList = CardLists.filter(typeList, crd -> crd.canBeControlledBy(player));
final CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, source, ability);
if (typeList.size() < c) {
return null;
@@ -335,26 +328,31 @@ public class AiCostDecision extends CostDecisionMakerBase {
return res.isEmpty() ? null : PaymentDecision.card(res);
}
@Override
public PaymentDecision visit(CostGainLife cost) {
final List<Player> oppsThatCanGainLife = Lists.newArrayList();
for (final Player opp : cost.getPotentialTargets(player, ability)) {
for (final Player opp : cost.getPotentialTargets(player, source)) {
if (opp.canGainLife()) {
oppsThatCanGainLife.add(opp);
}
}
if (oppsThatCanGainLife.isEmpty()) {
if (oppsThatCanGainLife.size() == 0) {
return null;
}
return PaymentDecision.players(oppsThatCanGainLife);
}
@Override
public PaymentDecision visit(CostMill cost) {
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
CardCollectionView topLib = player.getCardsIn(ZoneType.Library, c);
return topLib.size() < c ? null : PaymentDecision.number(c);
@@ -367,43 +365,56 @@ public class AiCostDecision extends CostDecisionMakerBase {
@Override
public PaymentDecision visit(CostPayLife cost) {
int c = cost.getAbilityAmount(ability);
if (!player.canPayLife(c, isEffect(), ability)) {
Integer c = cost.convertAmount();
if (c == null) {
// Generalize cost
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
if (!player.canPayLife(c)) {
return null;
}
// activator.payLife(c, null);
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostPayEnergy cost) {
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
if (!player.canPayEnergy(c)) {
return null;
}
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostPutCardToLib cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
Integer c = cost.convertAmount();
final Game game = player.getGame();
CardCollection chosen = new CardCollection();
CardCollectionView list;
if (cost.isSameZone()) {
list = game.getCardsIn(cost.getFrom());
} else {
list = player.getCardsIn(cost.getFrom());
list = new CardCollection(game.getCardsIn(cost.getFrom()));
}
else {
list = new CardCollection(player.getCardsIn(cost.getFrom()));
}
int c = cost.getAbilityAmount(ability);
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
list = CardLists.getValidCards(list, cost.getType().split(";"), player, source, ability);
if (cost.isSameZone()) {
// Jötun Grunt
// Jotun Grunt
// TODO: improve AI
final FCollectionView<Player> players = game.getPlayers();
for (Player p : players) {
@@ -414,7 +425,8 @@ public class AiCostDecision extends CostDecisionMakerBase {
}
}
chosen = chosen.subList(0, c);
} else {
}
else {
chosen = ComputerUtil.choosePutToLibraryFrom(player, cost.getFrom(), cost.getType(), source, ability.getTargetCard(), c, ability);
}
return chosen.isEmpty() ? null : PaymentDecision.card(chosen);
@@ -432,12 +444,14 @@ public class AiCostDecision extends CostDecisionMakerBase {
Card card;
if (cost.getType().equals("Creature.YouCtrl")) {
card = ComputerUtilCard.getWorstCreatureAI(typeList);
} else {
}
else {
card = ComputerUtilCard.getWorstPermanentAI(typeList, false, false, false, false);
}
return PaymentDecision.card(card);
}
@Override
public PaymentDecision visit(CostTap cost) {
return PaymentDecision.number(0);
@@ -445,16 +459,39 @@ public class AiCostDecision extends CostDecisionMakerBase {
@Override
public PaymentDecision visit(CostTapType cost) {
final String amount = cost.getAmount();
Integer c = cost.convertAmount();
String type = cost.getType();
boolean isVehicle = type.contains("+withTotalPowerGE");
CardCollection exclude = new CardCollection();
exclude.addAll(tapped);
if (c == null && !isVehicle) {
c = AbilityUtils.calculateAmount(source, amount, ability);
}
if (type.contains("sharesCreatureTypeWith")) {
return null;
}
if ("DontPayTapCostWithManaSources".equals(source.getSVar("AIPaymentPreference"))) {
CardCollectionView toExclude =
CardLists.getValidCards(player.getCardsIn(ZoneType.Battlefield), type.split(";"),
ability.getActivatingPlayer(), ability.getHostCard(), ability);
toExclude = CardLists.filter(toExclude, new Predicate<Card>() {
@Override
public boolean apply(Card card) {
for (final SpellAbility sa : card.getSpellAbilities()) {
if (sa.isManaAbility() && sa.getPayCosts().hasTapCost()) {
return true;
}
}
return false;
}
});
exclude.addAll(toExclude);
}
String totalP = "";
CardCollectionView totap;
if (isVehicle) {
@@ -462,7 +499,6 @@ public class AiCostDecision extends CostDecisionMakerBase {
type = TextUtil.fastReplace(type, "+withTotalPowerGE", "");
totap = ComputerUtil.chooseTapTypeAccumulatePower(player, type, ability, !cost.canTapSource, Integer.parseInt(totalP), exclude);
} else {
int c = cost.getAbilityAmount(ability);
totap = ComputerUtil.chooseTapType(player, type, source, !cost.canTapSource, c, exclude, ability);
}
@@ -474,24 +510,29 @@ public class AiCostDecision extends CostDecisionMakerBase {
return PaymentDecision.card(totap);
}
@Override
public PaymentDecision visit(CostSacrifice cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
if (cost.getType().equals("OriginalHost")) {
return PaymentDecision.card(ability.getOriginalHost());
return PaymentDecision.card(ability.getHostCard());
}
if (cost.getAmount().equals("All")) {
// Does the AI want to use Sacrifice All?
return null;
}
int c = cost.getAbilityAmount(ability);
final String amount = cost.getAmount();
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, amount, ability);
}
final AiController aic = ((PlayerControllerAi)player.getController()).getAi();
CardCollectionView list = aic.chooseSacrificeType(cost.getType(), ability, isEffect(), c, null);
return list == null ? null : PaymentDecision.card(list);
CardCollectionView list = aic.chooseSacrificeType(cost.getType(), ability, c);
return PaymentDecision.card(list);
}
@Override
@@ -499,7 +540,10 @@ public class AiCostDecision extends CostDecisionMakerBase {
if (cost.payCostFromSource())
return PaymentDecision.card(source);
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
CardCollectionView res = ComputerUtil.chooseReturnType(player, cost.getType(), source, ability.getTargetCard(), c, ability);
return res.isEmpty() ? null : PaymentDecision.card(res);
@@ -521,42 +565,28 @@ public class AiCostDecision extends CostDecisionMakerBase {
return PaymentDecision.card(hand);
}
if (cost.getRevealFrom().size() == 2 && cost.getRevealFrom().containsAll(Arrays.asList(ZoneType.Hand, ZoneType.Battlefield))) { // RevealOrChoose
String aiLogic = ability.getParamOrDefault("AILogic", "");
hand = CardLists.getValidCards(hand, type.split(";"), player, source, ability);
if (aiLogic.startsWith("PowerAtLeast.")) {
int minPower = Integer.parseInt(aiLogic.substring(aiLogic.indexOf(".") + 1));
hand = CardLists.filterPower(hand, minPower);
}
return hand.isEmpty() ? null : PaymentDecision.card(getBestCreatureAI(hand));
}
if (cost.getType().equals("SameColor")) {
return null;
}
if (cost.getRevealFrom().get(0).equals(ZoneType.Exile)) {
if (cost.getRevealFrom().equals(ZoneType.Exile)) {
hand = CardLists.getValidCards(hand, type.split(";"), player, source, ability);
return PaymentDecision.card(getBestCreatureAI(hand));
}
int c = cost.getAbilityAmount(ability);
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, cost.getAmount(), ability);
}
final AiController aic = ((PlayerControllerAi)player.getController()).getAi();
return PaymentDecision.card(aic.getCardsToDiscard(c, type.split(";"), ability));
}
@Override
public PaymentDecision visit(CostRevealChosen cost) {
return PaymentDecision.number(1);
}
protected int removeCounter(GameEntityCounterTable table, List<Card> prefs, CounterEnumType cType, int stillToRemove) {
int removed = 0;
if (!prefs.isEmpty() && stillToRemove > 0) {
prefs.sort(CardPredicates.compareByCounterType(cType));
Collections.sort(prefs, CardPredicates.compareByCounterType(cType));
for (Card prefCard : prefs) {
// already enough removed
@@ -566,7 +596,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
int thisRemove = Math.min(prefCard.getCounters(cType), stillToRemove);
if (thisRemove > 0) {
removed += thisRemove;
table.put(null, prefCard, cType, thisRemove);
table.put(prefCard, CounterType.get(cType), thisRemove);
}
}
}
@@ -575,8 +605,9 @@ public class AiCostDecision extends CostDecisionMakerBase {
@Override
public PaymentDecision visit(CostRemoveAnyCounter cost) {
final int c = cost.getAbilityAmount(ability);
final Card originalHost = ObjectUtils.getIfNull(ability.getOriginalHost(), source);
final String amount = cost.getAmount();
final int c = AbilityUtils.calculateAmount(source, amount, ability);
final Card originalHost = ability.getOriginalOrHost();
if (c <= 0) {
return null;
@@ -597,6 +628,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
// currently if amount is bigger than one,
// it tries to remove all counters from one source and type at once
int toRemove = 0;
final GameEntityCounterTable table = new GameEntityCounterTable();
@@ -630,7 +662,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
int thisRemove = Math.min(card.getCounters(ctype), c - toRemove);
if (thisRemove > 0) {
toRemove += thisRemove;
table.put(null, card, ctype, thisRemove);
table.put(card, ctype, thisRemove);
}
}
}
@@ -638,24 +670,27 @@ public class AiCostDecision extends CostDecisionMakerBase {
// filter for negative counters
if (c > toRemove && cost.counter == null) {
List<Card> negatives = CardLists.filter(typeList, crd -> {
List<Card> negatives = CardLists.filter(typeList, new Predicate<Card>() {
@Override
public boolean apply(final Card crd) {
for (CounterType cType : table.filterToRemove(crd).keySet()) {
if (ComputerUtil.isNegativeCounter(cType, crd)) {
return true;
}
}
return false;
}
});
if (!negatives.isEmpty()) {
// TODO sort negatives to remove from best Cards first?
for (final Card crd : negatives) {
for (Map.Entry<CounterType, Integer> e : table.filterToRemove(crd).entrySet()) {
if (ComputerUtil.isNegativeCounter(e.getKey(), crd) && crd.canRemoveCounters(e.getKey())) {
if (ComputerUtil.isNegativeCounter(e.getKey(), crd)) {
int over = Math.min(e.getValue(), c - toRemove);
if (over > 0) {
toRemove += over;
table.put(null, crd, e.getKey(), over);
table.put(crd, e.getKey(), over);
}
}
}
@@ -666,13 +701,16 @@ public class AiCostDecision extends CostDecisionMakerBase {
// filter for useless counters
// they have no effect on the card, if they are there or removed
if (c > toRemove && cost.counter == null) {
List<Card> useless = CardLists.filter(typeList, crd -> {
List<Card> useless = CardLists.filter(typeList, new Predicate<Card>() {
@Override
public boolean apply(final Card crd) {
for (CounterType ctype : table.filterToRemove(crd).keySet()) {
if (ComputerUtil.isUselessCounter(ctype, crd)) {
return true;
}
}
return false;
}
});
if (!useless.isEmpty()) {
@@ -682,7 +720,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
int over = Math.min(e.getValue(), c - toRemove);
if (over > 0) {
toRemove += over;
table.put(null, crd, e.getKey(), over);
table.put(crd, e.getKey(), over);
}
}
}
@@ -700,7 +738,9 @@ public class AiCostDecision extends CostDecisionMakerBase {
// try to remove Quest counter on something with enough counters for the
// effect to continue
if (c > toRemove && (cost.counter == null || cost.counter.is(CounterEnumType.QUEST))) {
List<Card> prefs = CardLists.filter(typeList, crd -> {
List<Card> prefs = CardLists.filter(typeList, new Predicate<Card>() {
@Override
public boolean apply(final Card crd) {
// a Card without MaxQuestEffect doesn't need any Quest
// counters
int e = 0;
@@ -708,8 +748,9 @@ public class AiCostDecision extends CostDecisionMakerBase {
e = Integer.parseInt(crd.getSVar("MaxQuestEffect"));
}
return crd.getCounters(CounterEnumType.QUEST) > e;
}
});
prefs.sort(Collections.reverseOrder(CardPredicates.compareByCounterType(CounterEnumType.QUEST)));
Collections.sort(prefs, Collections.reverseOrder(CardPredicates.compareByCounterType(CounterEnumType.QUEST)));
for (final Card crd : prefs) {
int e = 0;
@@ -719,7 +760,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
int over = Math.min(crd.getCounters(CounterEnumType.QUEST) - e, c - toRemove);
if (over > 0) {
toRemove += over;
table.put(null, crd, CounterEnumType.QUEST, over);
table.put(crd, CounterType.get(CounterEnumType.QUEST), over);
}
}
}
@@ -732,6 +773,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
toRemove += removeCounter(table, prefs, CounterEnumType.LORE, c - toRemove);
}
// TODO add logic to remove positive counters?
if (c > toRemove && cost.counter != null) {
// TODO add logic for Ooze Flux, should probably try to make a token as big as possible
@@ -742,7 +784,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
int thisRemove = Math.min(card.getCounters(cost.counter), c - toRemove);
if (thisRemove > 0) {
toRemove += thisRemove;
table.put(null, card, cost.counter, thisRemove);
table.put(card, cost.counter, thisRemove);
}
}
}
@@ -756,29 +798,23 @@ public class AiCostDecision extends CostDecisionMakerBase {
int thisRemove = Math.min(e.getValue(), c - toRemove);
if (thisRemove > 0) {
toRemove += thisRemove;
table.put(null, card, e.getKey(), thisRemove);
table.put(card, e.getKey(), thisRemove);
}
}
}
}
// if table is empty, then no counter was removed
// if table is empty, than no counter was removed
return table.isEmpty() ? null : PaymentDecision.counters(table);
}
@Override
public PaymentDecision visit(CostRemoveCounter cost) {
final String amount = cost.getAmount();
Integer c = cost.convertAmount();
final String type = cost.getType();
final GameEntityCounterTable counterTable = new GameEntityCounterTable();
// TODO Help AI filter card with most useless counters and put those counters in countertable for things like
// Moxite Refinery, similar to CostRemoveAnyCounter
// Probably a lot of that decision making can be re-used or pulled out for both PaymentDecisions to use
if (cost.counter == null) return null;
int c;
if (c == null) {
final String sVar = ability.getSVar(amount);
if (amount.equals("All")) {
c = source.getCounters(cost.counter);
@@ -792,7 +828,8 @@ public class AiCostDecision extends CostDecisionMakerBase {
}
}
} else {
c = cost.getAbilityAmount(ability);
c = AbilityUtils.calculateAmount(source, amount, ability);
}
}
if (!cost.payCostFromSource()) {
@@ -804,8 +841,7 @@ public class AiCostDecision extends CostDecisionMakerBase {
}
for (Card card : typeList) {
if (card.getCounters(cost.counter) >= c) {
counterTable.put(null, card, cost.counter, c);
return PaymentDecision.counters(counterTable);
return PaymentDecision.card(card, c);
}
}
return null;
@@ -816,13 +852,16 @@ public class AiCostDecision extends CostDecisionMakerBase {
return null;
}
counterTable.put(null, source, cost.counter, c);
return PaymentDecision.counters(counterTable);
return PaymentDecision.card(source, c);
}
@Override
public PaymentDecision visit(CostUntapType cost) {
int c = cost.getAbilityAmount(ability);
final String amount = cost.getAmount();
Integer c = cost.convertAmount();
if (c == null) {
c = AbilityUtils.calculateAmount(source, amount, ability);
}
CardCollectionView list = ComputerUtil.chooseUntapType(player, cost.getType(), source, cost.canUntapSource, c, ability);
@@ -839,19 +878,14 @@ public class AiCostDecision extends CostDecisionMakerBase {
return PaymentDecision.number(0);
}
@Override
public PaymentDecision visit(CostPayShards cost) {
return PaymentDecision.number(0);
}
@Override
public PaymentDecision visit(CostUnattach cost) {
final CardCollection cardToUnattach = cost.findCardToUnattach(source, player, ability);
if (cardToUnattach.isEmpty()) {
final Card cardToUnattach = cost.findCardToUnattach(source, player, ability);
if (cardToUnattach == null) {
// We really shouldn't be able to get here if there's nothing to unattach
return null;
}
return PaymentDecision.card(cardToUnattach.getFirst());
return PaymentDecision.card(cardToUnattach);
}
@Override
@@ -859,3 +893,4 @@ public class AiCostDecision extends CostDecisionMakerBase {
return false;
}
}

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
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;
};
}
CurseEffects
}

View File

@@ -11,8 +11,11 @@ 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) -> {
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);
@@ -29,6 +32,7 @@ public final class AiPlayerPredicates {
v1 = ComputerUtilCard.evaluatePermanentList(list1);
}
return Integer.compare(v0, v1);
}
};
}
}

View File

@@ -17,18 +17,19 @@
*/
package forge.ai;
import forge.LobbyPlayer;
import forge.util.Aggregates;
import forge.util.FileUtil;
import forge.util.TextUtil;
import org.apache.commons.lang3.ArrayUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import forge.LobbyPlayer;
import forge.util.Aggregates;
import forge.util.FileUtil;
import forge.util.TextUtil;
/**
* Holds default AI personality profile values in an enum.
* Loads profile from the given text file when setProfile is called.
@@ -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) {
private static final Map<AiProps, String> loadProfile(final String profileName) {
Map<AiProps, String> profileMap = new HashMap<>();
List<String> lines = FileUtil.readFile(buildFileName(profileName));
for (String line : lines) {
if (line.startsWith("#") || (line.length() == 0)) {
continue;
}
@@ -138,7 +120,8 @@ public class AiProfileUtil {
* @return ArrayList<String> - an array of strings containing all
* available profiles.
*/
public static List<String> getAvailableProfiles() {
public static List<String> getAvailableProfiles()
{
final List<String> availableProfiles = new ArrayList<>();
final File dir = new File(AI_PROFILE_DIR);
@@ -146,9 +129,9 @@ public class AiProfileUtil {
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()));
}
}
}

View File

@@ -134,18 +134,7 @@ public enum AiProps { /** */
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");
BLINK_RELOAD_PLANESWALKER_LOYALTY_DIFF("2"); /** */
// 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,9 +1,9 @@
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;
@@ -14,14 +14,8 @@ 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;
@@ -32,14 +26,23 @@ public class ComputerUtilAbility {
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()) {
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, false, c.getFirstSpellAbility());
}
return player.canPlayLand(c);
}
});
final CardCollection landsNotInHand = new CardCollection(player.getCardsIn(ZoneType.Graveyard));
@@ -48,7 +51,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,14 +68,14 @@ public class ComputerUtilAbility {
CardCollection all = new CardCollection(player.getCardsIn(ZoneType.Hand));
all.addAll(player.getCardsIn(ZoneType.Graveyard));
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()) {
if (!p.getCardsIn(ZoneType.Library).isEmpty()) {
all.add(p.getCardsIn(ZoneType.Library).get(0));
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;
}
@@ -96,7 +99,7 @@ public class ComputerUtilAbility {
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) {
@@ -123,10 +126,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 +149,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;
}
@@ -172,12 +171,8 @@ public class ComputerUtilAbility {
return sa;
}
public static Card getAbilitySource(SpellAbility sa) {
return sa.getOriginalHost() != null ? sa.getOriginalHost() : sa.getHostCard();
}
public static String getAbilitySourceName(SpellAbility sa) {
final Card c = getAbilitySource(sa);
final Card c = sa.getOriginalOrHost();
return c != null ? c.getName() : "";
}
@@ -201,7 +196,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 +210,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,52 @@
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.Card;
import forge.game.card.CardCollection;
import forge.game.card.CardCollectionView;
import forge.game.card.CardFactoryUtil;
import forge.game.card.CardLists;
import forge.game.card.CardPredicates.Presets;
import forge.game.card.CardUtil;
import forge.game.card.CounterEnumType;
import forge.game.card.CounterType;
import forge.game.combat.Combat;
import forge.game.cost.*;
import forge.game.cost.Cost;
import forge.game.cost.CostDamage;
import forge.game.cost.CostDiscard;
import forge.game.cost.CostPart;
import forge.game.cost.CostPayLife;
import forge.game.cost.CostPayment;
import forge.game.cost.CostPutCounter;
import forge.game.cost.CostRemoveAnyCounter;
import forge.game.cost.CostRemoveCounter;
import forge.game.cost.CostSacrifice;
import forge.game.cost.CostTapType;
import forge.game.cost.PaymentDecision;
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;
public class ComputerUtilCost {
private static boolean suppressRecursiveSacCostCheck = false;
public static void setSuppressRecursiveSacCostCheck(boolean shouldSuppress) {
suppressRecursiveSacCostCheck = shouldSuppress;
}
/**
* Check add m1 m1 counter cost.
@@ -51,7 +62,8 @@ 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)) {
@@ -75,9 +87,11 @@ public class ComputerUtilCost {
if (cost == null) {
return true;
}
final AiCostDecision decision = new AiCostDecision(sa.getActivatingPlayer(), sa, false);
final AiCostDecision decision = new AiCostDecision(sa.getActivatingPlayer(), sa);
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)) {
@@ -104,7 +118,9 @@ public class ComputerUtilCost {
&& !source.hasKeyword(Keyword.UNDYING)) {
return false;
}
} else if (part instanceof CostRemoveAnyCounter remCounter) {
} else if (part instanceof CostRemoveAnyCounter) {
final CostRemoveAnyCounter remCounter = (CostRemoveAnyCounter) part;
PaymentDecision pay = decision.visit(remCounter);
return pay != null;
}
@@ -121,39 +137,28 @@ public class ComputerUtilCost {
* the source
* @return true, if successful
*/
public static boolean checkDiscardCost(final Player ai, final Cost cost, final Card source, SpellAbility sa) {
if (cost == null) {
if (cost == null || source.hasSVar("AISkipDiscardCostCheck") /* FIXME: should not be needed! */ ) {
return true;
}
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")) {
if (type.equals("CARDNAME") && 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);
final CardCollection typeList = CardLists.getValidCards(hand, type.split(","), source.getController(), source, sa);
if (typeList.size() > ai.getMaxHandSize()) {
continue;
}
num = AbilityUtils.calculateAmount(source, disc.getAmount(), sa);
}
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) {
@@ -178,13 +183,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 +221,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 +242,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 +256,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 +270,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, sourceAbility);
int count = 0;
while (count < amount) {
@@ -334,14 +303,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 +316,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, sourceAbility);
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 +337,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.
*
@@ -416,91 +410,35 @@ public class ComputerUtilCost {
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;
}
/**
* 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;
if (part instanceof CostPayLife) {
if (!ai.cantLoseForZeroOrLessLife()) {
continue;
}
final int remainingLife = ai.getLife();
final int lifeCost = 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
}
}
return false;
}
// 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);
}
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,20 +451,15 @@ 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) {
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)) {
@@ -562,7 +495,7 @@ public class ComputerUtilCost {
// Try not to lose Planeswalker if not threatened
if (sa.isPwAbility()) {
for (final CostPart part : cost.getCostParts()) {
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
@@ -576,57 +509,151 @@ public class ComputerUtilCost {
}
}
// 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)) {
// 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().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");
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;
}
// 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())) {
// 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;
}
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()) {
} else if ("RiskFactor".equals(aiLogic)) {
final Player activator = sa.getActivatingPlayer();
if (!activator.canDraw() || activator.hasKeyword("You can't draw more than one card each turn.")) {
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).isEmpty()
&& AbilityUtils.getDefinedCards(source, sa.getParam("Defined"), sa).get(0).isToken()) {
return false;
} else if ("LowPriority".equals(aiLogic) && MyRandom.getRandom().nextInt(100) < 67) {
return false;
}
// 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);
// 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, sa))
&& (!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") || (payer.getWeakestOpponent().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) {
@@ -655,35 +682,34 @@ public class ComputerUtilCost {
return false;
}
public static int getMaxXValue(SpellAbility sa, Player ai, final boolean effect) {
public static int getMaxXValue(SpellAbility sa, Player ai) {
final Card source = sa.getHostCard();
SpellAbility root = sa.getRootAbility();
final Cost abCost = root.getPayCosts();
final SpellAbility root = sa.getRootAbility();
final Cost abCost = sa.getPayCosts();
if (abCost == null || !abCost.hasXInAnyCostPart()) {
return 0;
}
Integer val = null;
if (root.costHasManaX()) {
val = ComputerUtilMana.determineLeftoverMana(root, ai, effect);
if (sa.costHasManaX()) {
val = ComputerUtilMana.determineLeftoverMana(root, ai);
}
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());
val = ObjectUtils.min(val, CardUtil.getValidCardsToTarget(sa.getTargetRestrictions(), 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, AbilityUtils.calculateAmount(sa.getHostCard(), "Count$" + sa.getParam("AIMaxTgtsCount"), sa));
}
}
val = ObjectUtils.min(val, abCost.getMaxForNonManaX(root, ai, effect));
val = ObjectUtils.min(val, abCost.getMaxForNonManaX(root, ai));
if (val != null && val > 0) {
// filter cost parts for preferences, don't choose X > than possible preferences
@@ -713,12 +739,4 @@ public class ComputerUtilCost {
}
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.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,33 +27,27 @@ 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.")) {
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");
@@ -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,8 +75,8 @@ 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");
}
}
@@ -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)) {
@@ -141,8 +134,6 @@ public class CreatureEvaluator implements Function<Card, Integer> {
// 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,68 +144,63 @@ 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)) {
} 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 (!mAEnt.isEmpty()) {
} 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.")) {
} 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.isUntapped()) {
value += addValue(1, "untapped");
if (c.hasKeyword("CARDNAME can't attack or block.")) {
value = addValue(50 + (c.getCMC() * 5), "useless"); // reset everything - useless
}
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()) {
@@ -222,62 +208,27 @@ public class CreatureEvaluator implements Function<Card, Integer> {
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");
}
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;
// paired creatures are more valuable because they grant a bonus to the other creature
if (c.isPaired()) {
value += addValue(14, "paired");
}
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;
@@ -293,7 +244,7 @@ public class CreatureEvaluator implements Function<Card, Integer> {
&& (!sa.hasParam("Defined") || "Self".equals(sa.getParam("Defined")))) {
if (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);
if (energy > 0) {
@@ -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

View File

@@ -25,6 +25,7 @@ public class LobbyPlayerAi extends LobbyPlayer implements IGameEntitiesFactory {
public boolean isAllowCheatShuffle() {
return allowCheatShuffle;
}
public void setAllowCheatShuffle(boolean allowCheatShuffle) {
this.allowCheatShuffle = allowCheatShuffle;
}
@@ -32,6 +33,7 @@ public class LobbyPlayerAi extends LobbyPlayer implements IGameEntitiesFactory {
public void setAiProfile(String profileName) {
aiProfile = profileName;
}
public String getAiProfile() {
return aiProfile;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +1,28 @@
package forge.ai;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import forge.ai.ability.TokenAi;
import forge.game.Game;
import forge.game.ability.AbilityUtils;
import forge.game.ability.ApiType;
import forge.game.card.*;
import forge.game.card.Card;
import forge.game.card.CardCollection;
import forge.game.card.CardLists;
import forge.game.card.CardPredicates;
import forge.game.card.CardUtil;
import forge.game.card.CounterEnumType;
import forge.game.card.CounterType;
import forge.game.combat.Combat;
import forge.game.keyword.Keyword;
import forge.game.phase.PhaseHandler;
import forge.game.phase.PhaseType;
import forge.game.player.Player;
import forge.game.spellability.SpellAbility;
import forge.game.zone.ZoneType;
import forge.util.Aggregates;
import forge.util.Expressions;
import java.util.List;
/*
* This class contains logic which is shared by several cards with different ability types (e.g. AF ChangeZone / AF Destroy)
@@ -42,7 +46,7 @@ public class SpecialAiLogic {
return false;
}
List<Card> targetable = CardUtil.getValidCardsToTarget(sa);
List<Card> targetable = CardUtil.getValidCardsToTarget(sa.getTargetRestrictions(), sa);
CardCollection listOpp = CardLists.filterControlledBy(targetable, ai.getOpponents());
if (isDestroy) {
@@ -90,10 +94,13 @@ public class SpecialAiLogic {
bestOwnCardToUpgrade = Iterables.getFirst(CardLists.getKeyword(listOwn, Keyword.INDESTRUCTIBLE), null);
}
if (bestOwnCardToUpgrade == null) {
bestOwnCardToUpgrade = ComputerUtilCard.getWorstCreatureAI(CardLists.filter(listOwn, card -> card.isCreature()
&& (ComputerUtilCard.isUselessCreature(ai, card)
|| ComputerUtilCard.evaluateCreature(token) > 2 * ComputerUtilCard.evaluateCreature(card))
));
bestOwnCardToUpgrade = ComputerUtilCard.getWorstCreatureAI(CardLists.filter(listOwn, new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return card.isCreature() && (ComputerUtilCard.isUselessCreature(ai, card)
|| ComputerUtilCard.evaluateCreature(token) > 2 * ComputerUtilCard.evaluateCreature(card));
}
}));
}
if (bestOwnCardToUpgrade != null) {
if (ComputerUtilCard.isUselessCreature(ai, bestOwnCardToUpgrade) || (ph.getPhase().isAfter(PhaseType.COMBAT_END) || !ph.isPlayerTurn(ai))) {
@@ -141,9 +148,14 @@ public class SpecialAiLogic {
if (indestructible || (source.getNetToughness() <= dmg && source.getNetToughness() + toughnessBonus * numCreatsToSac > dmg)) {
final CardCollection sacFodder = CardLists.filter(ai.getCreaturesInPlay(),
card -> ComputerUtilCard.isUselessCreature(ai, card)
new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return ComputerUtilCard.isUselessCreature(ai, card)
|| card.hasSVar("SacMe")
|| ComputerUtilCard.evaluateCreature(card) < selfEval // Maybe around 150 is OK?
|| ComputerUtilCard.evaluateCreature(card) < selfEval; // Maybe around 150 is OK?
}
}
);
return sacFodder.size() >= numCreatsToSac;
}
@@ -171,7 +183,7 @@ public class SpecialAiLogic {
final boolean isInfect = source.hasKeyword(Keyword.INFECT); // Flesh-Eater Imp
int lethalDmg = isInfect ? 10 - defPlayer.getPoisonCounters() : defPlayer.getLife();
if (isInfect && !combat.getDefenderByAttacker(source).canReceiveCounters(CounterEnumType.POISON)) {
if (isInfect && !combat.getDefenderByAttacker(source).canReceiveCounters(CounterType.get(CounterEnumType.POISON))) {
lethalDmg = Integer.MAX_VALUE; // won't be able to deal poison damage to kill the opponent
}
@@ -187,16 +199,21 @@ public class SpecialAiLogic {
// We have already attacked. Thus, see if we have a creature to sac that is worse to lose
// than the card we attacked with.
final CardCollection sacTgts = CardLists.filter(ai.getCreaturesInPlay(),
card -> ComputerUtilCard.isUselessCreature(ai, card)
|| ComputerUtilCard.evaluateCreature(card) < selfEval
new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return ComputerUtilCard.isUselessCreature(ai, card)
|| ComputerUtilCard.evaluateCreature(card) < selfEval;
}
}
);
if (sacTgts.isEmpty()) {
return false;
}
final int minDefT = Aggregates.min(combat.getBlockers(source), Card::getNetToughness);
final int DefP = indestructible ? 0 : Aggregates.sum(combat.getBlockers(source), Card::getNetPower);
final int minDefT = Aggregates.min(combat.getBlockers(source), CardPredicates.Accessors.fnGetNetToughness);
final int DefP = indestructible ? 0 : Aggregates.sum(combat.getBlockers(source), CardPredicates.Accessors.fnGetNetPower);
// Make sure we don't over-sacrifice, only sac until we can survive and kill a creature
return source.getNetToughness() - source.getDamage() <= DefP || source.getNetCombatDamage() < minDefT;
@@ -204,9 +221,14 @@ public class SpecialAiLogic {
} else {
// We can't deal lethal, check if there's any sac fodder than can be used for other circumstances
final CardCollection sacFodder = CardLists.filter(ai.getCreaturesInPlay(),
card -> ComputerUtilCard.isUselessCreature(ai, card)
new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return ComputerUtilCard.isUselessCreature(ai, card)
|| card.hasSVar("SacMe")
|| ComputerUtilCard.evaluateCreature(card) < selfEval // Maybe around 150 is OK?
|| ComputerUtilCard.evaluateCreature(card) < selfEval; // Maybe around 150 is OK?
}
}
);
return !sacFodder.isEmpty();
@@ -214,7 +236,7 @@ public class SpecialAiLogic {
}
// A logic for cards that say "Sacrifice a creature: put X +1/+1 counters on CARDNAME" (e.g. Falkenrath Aristocrat)
public static AiAbilityDecision doAristocratWithCountersLogic(final Player ai, final SpellAbility sa) {
public static boolean doAristocratWithCountersLogic(final Player ai, final SpellAbility sa) {
final Card source = sa.getHostCard();
final String logic = sa.getParam("AILogic"); // should not even get here unless there's an Aristocrats logic applied
final boolean isDeclareBlockers = ai.getGame().getPhaseHandler().is(PhaseType.COMBAT_DECLARE_BLOCKERS);
@@ -222,14 +244,14 @@ public class SpecialAiLogic {
final int numOtherCreats = Math.max(0, ai.getCreaturesInPlay().size() - 1);
if (numOtherCreats == 0) {
// Cut short if there's nothing to sac at all
return new AiAbilityDecision(0, AiPlayDecision.CantAfford);
return false;
}
// Check if the standard Aristocrats logic applies first (if in the right conditions for it)
final boolean isThreatened = ComputerUtil.predictThreatenedObjects(ai, null, true).contains(source);
if (isDeclareBlockers || isThreatened) {
if (doAristocratLogic(ai, sa)) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return true;
}
}
@@ -247,7 +269,7 @@ public class SpecialAiLogic {
if (countersSa == null) {
// Shouldn't get here if there is no PutCounter subability (wrong AI logic specified?)
System.err.println("Warning: AILogic AristocratCounters was specified on " + source + ", but there was no PutCounter SA in chain!");
return new AiAbilityDecision(0, AiPlayDecision.CantPlaySa);
return false;
}
final Game game = ai.getGame();
@@ -263,7 +285,7 @@ public class SpecialAiLogic {
relevantCreats.remove(source);
if (relevantCreats.isEmpty()) {
// No relevant creatures to sac
return new AiAbilityDecision(0, AiPlayDecision.MissingNeededCards);
return false;
}
int numCtrs = AbilityUtils.calculateAmount(source, countersSa.getParam("CounterNum"), countersSa);
@@ -277,149 +299,74 @@ public class SpecialAiLogic {
final boolean isInfect = source.hasKeyword(Keyword.INFECT);
int lethalDmg = isInfect ? 10 - defPlayer.getPoisonCounters() : defPlayer.getLife();
if (isInfect && !combat.getDefenderByAttacker(source).canReceiveCounters(CounterEnumType.POISON)) {
if (isInfect && !combat.getDefenderByAttacker(source).canReceiveCounters(CounterType.get(CounterEnumType.POISON))) {
lethalDmg = Integer.MAX_VALUE; // won't be able to deal poison damage to kill the opponent
}
// Check if there's anything that will die anyway that can be eaten to gain a perma-bonus
final CardCollection forcedSacTgts = CardLists.filter(relevantCreats,
card -> ComputerUtil.predictThreatenedObjects(ai, null, true).contains(card)
|| (combat.isAttacking(card) && combat.isBlocked(card) && ComputerUtilCombat.combatantWouldBeDestroyed(ai, card, combat))
new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return ComputerUtil.predictThreatenedObjects(ai, null, true).contains(card)
|| (combat.isAttacking(card) && combat.isBlocked(card) && ComputerUtilCombat.combatantWouldBeDestroyed(ai, card, combat));
}
}
);
if (!forcedSacTgts.isEmpty()) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return true;
}
final int numCreatsToSac = Math.max(0, (lethalDmg - source.getNetCombatDamage()) / numCtrs);
if (defTappedOut || numCreatsToSac < relevantCreats.size() / 2) {
if (source.getNetCombatDamage() < lethalDmg
&& source.getNetCombatDamage() + relevantCreats.size() * numCtrs >= lethalDmg) {
return new AiAbilityDecision(100, AiPlayDecision.ImpactCombat);
}
return new AiAbilityDecision(0, AiPlayDecision.DoesntImpactCombat);
return source.getNetCombatDamage() < lethalDmg
&& source.getNetCombatDamage() + relevantCreats.size() * numCtrs >= lethalDmg;
} else {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
return false;
}
} else {
// We have already attacked. Thus, see if we have a creature to sac that is worse to lose
// than the card we attacked with. Since we're getting a permanent bonus, consider sacrificing
// things that are also threatened to be destroyed anyway.
final CardCollection sacTgts = CardLists.filter(relevantCreats,
card -> ComputerUtilCard.isUselessCreature(ai, card)
new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return ComputerUtilCard.isUselessCreature(ai, card)
|| ComputerUtilCard.evaluateCreature(card) < selfEval
|| ComputerUtil.predictThreatenedObjects(ai, null, true).contains(card)
|| ComputerUtil.predictThreatenedObjects(ai, null, true).contains(card);
}
}
);
if (sacTgts.isEmpty()) {
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
return false;
}
final boolean sourceCantDie = ComputerUtilCombat.combatantCantBeDestroyed(ai, source);
final int minDefT = Aggregates.min(combat.getBlockers(source), Card::getNetToughness);
final int DefP = sourceCantDie ? 0 : Aggregates.sum(combat.getBlockers(source), Card::getNetPower);
final boolean sourceCantDie = ComputerUtilCombat.attackerCantBeDestroyedInCombat(ai, source);
final int minDefT = Aggregates.min(combat.getBlockers(source), CardPredicates.Accessors.fnGetNetToughness);
final int DefP = sourceCantDie ? 0 : Aggregates.sum(combat.getBlockers(source), CardPredicates.Accessors.fnGetNetPower);
// Make sure we don't over-sacrifice, only sac until we can survive and kill a creature
if (source.getNetToughness() - source.getDamage() <= DefP || source.getNetCombatDamage() < minDefT) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
return source.getNetToughness() - source.getDamage() <= DefP || source.getNetCombatDamage() < minDefT;
}
} else {
// We can't deal lethal, check if there's any sac fodder than can be used for other circumstances
final boolean isBlocking = combat != null && combat.isBlocking(source);
final CardCollection sacFodder = CardLists.filter(relevantCreats,
card -> ComputerUtilCard.isUselessCreature(ai, card)
new Predicate<Card>() {
@Override
public boolean apply(Card card) {
return ComputerUtilCard.isUselessCreature(ai, card)
|| card.hasSVar("SacMe")
|| (isBlocking && ComputerUtilCard.evaluateCreature(card) < selfEval)
|| ComputerUtil.predictThreatenedObjects(ai, null, true).contains(card)
|| ComputerUtil.predictThreatenedObjects(ai, null, true).contains(card);
}
}
);
if (sacFodder.isEmpty()) {
return new AiAbilityDecision(0, AiPlayDecision.MissingNeededCards);
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return !sacFodder.isEmpty();
}
}
// AF Branch Counterspell with UnlessCost logic (Bring the Ending, Anticognition)
public static boolean doBranchCounterspellLogic(final Player ai, final SpellAbility sa) {
// TODO: this is an ugly hack that needs a rewrite if more cards are added with different SA setups or
// if this is to be made more generic in the future.
SpellAbility top = ComputerUtilAbility.getTopSpellAbilityOnStack(ai.getGame(), sa);
if (top == null || !sa.canTarget(top)) {
return false;
}
Card host = sa.getHostCard();
// pre-target the object to calculate the branch condition SVar, then clean up before running the real check
sa.getTargets().add(top);
int value = AbilityUtils.calculateAmount(sa.getHostCard(), sa.getParam("BranchConditionSVar"), sa);
sa.resetTargets();
String branchCompare = sa.getParamOrDefault("BranchConditionSVarCompare", "GE1");
String operator = branchCompare.substring(0, 2);
String operand = branchCompare.substring(2);
final int operandValue = AbilityUtils.calculateAmount(host, operand, sa);
boolean conditionMet = Expressions.compare(value, operator, operandValue);
SpellAbility falseSub = sa.getAdditionalAbility("FalseSubAbility"); // this ability has the UnlessCost part
boolean willPlay = false;
if (!conditionMet && falseSub.hasParam("UnlessCost")) {
// FIXME: We're emulating the UnlessCost on the SA to run the proper checks.
// This is hacky, but it works. Perhaps a cleaner way exists?
sa.getMapParams().put("UnlessCost", falseSub.getParam("UnlessCost"));
willPlay = SpellApiToAi.Converter.get(ApiType.Counter).canPlayWithSubs(ai, sa).willingToPlay();
sa.getMapParams().remove("UnlessCost");
} else {
willPlay = SpellApiToAi.Converter.get(ApiType.Counter).canPlayWithSubs(ai, sa).willingToPlay();
}
return willPlay;
}
public static boolean preferHasteForRiot(SpellAbility sa, Player player) {
// returning true means preferring Haste, returning false means preferring a +1/+1 counter
final Card host = sa.getHostCard();
final Game game = host.getGame();
final Card copy = CardCopyService.getLKICopy(host);
copy.setLastKnownZone(player.getZone(ZoneType.Battlefield));
// check state it would have on the battlefield
CardCollection preList = new CardCollection(copy);
game.getAction().checkStaticAbilities(false, Sets.newHashSet(copy), preList);
// reset again?
game.getAction().checkStaticAbilities(false);
// can't gain counters, use Haste
if (!copy.canReceiveCounters(CounterEnumType.P1P1)) {
return true;
}
// already has Haste, use counter
if (copy.hasKeyword(Keyword.HASTE)) {
return false;
}
// not AI turn
if (!game.getPhaseHandler().isPlayerTurn(player)) {
return false;
}
// not before Combat
if (!game.getPhaseHandler().getPhase().isBefore(PhaseType.COMBAT_DECLARE_ATTACKERS)) {
return false;
}
// TODO check other opponents too if able
final Player opp = player.getWeakestOpponent();
if (opp != null) {
// TODO add predict Combat Damage?
return opp.getLife() < copy.getNetPower();
}
// haste might not be good enough?
return false;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -13,8 +13,6 @@ import forge.card.mana.ManaCost;
import forge.card.mana.ManaCostParser;
import forge.game.GameEntity;
import forge.game.card.Card;
import forge.game.card.CardCopyService;
import forge.game.card.CardState;
import forge.game.card.CounterType;
import forge.game.cost.Cost;
import forge.game.mana.ManaCostBeingPaid;
@@ -24,13 +22,9 @@ import forge.game.player.Player;
import forge.game.player.PlayerActionConfirmMode;
import forge.game.player.PlayerController.BinaryChoiceType;
import forge.game.spellability.AbilitySub;
import forge.game.spellability.OptionalCost;
import forge.game.spellability.OptionalCostValue;
import forge.game.spellability.SpellAbility;
import forge.game.spellability.SpellAbilityCondition;
import forge.game.zone.ZoneType;
import forge.util.MyRandom;
import forge.util.collect.FCollectionView;
/**
* Base class for API-specific AI logic
@@ -39,81 +33,71 @@ import forge.util.collect.FCollectionView;
*/
public abstract class SpellAbilityAi {
public final AiAbilityDecision canPlayWithSubs(final Player aiPlayer, final SpellAbility sa) {
AiAbilityDecision decision = canPlay(aiPlayer, sa);
if (!decision.willingToPlay() && !"PlayForSub".equals(sa.getParam("AILogic"))) {
return decision;
public final boolean canPlayAIWithSubs(final Player aiPlayer, final SpellAbility sa) {
if (!canPlayAI(aiPlayer, sa)) {
return false;
}
final AbilitySub subAb = sa.getSubAbility();
if (subAb == null) {
return decision;
}
return chkDrawbackWithSubs(aiPlayer, subAb);
return subAb == null || chkDrawbackWithSubs(aiPlayer, subAb);
}
/**
* Handles the AI decision to play a "main" SpellAbility
*/
protected AiAbilityDecision canPlay(final Player ai, final SpellAbility sa) {
if (sa.getRestrictions() != null && !sa.getRestrictions().canPlay(sa.getHostCard(), sa)) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlaySa);
protected boolean canPlayAI(final Player ai, final SpellAbility sa) {
final Card source = sa.getHostCard();
if (sa.getRestrictions() != null && !sa.getRestrictions().canPlay(source, sa)) {
return false;
}
return canPlayWithoutRestrict(ai, sa);
}
protected AiAbilityDecision canPlayWithoutRestrict(final Player ai, final SpellAbility sa) {
protected boolean canPlayWithoutRestrict(final Player ai, final SpellAbility sa) {
final Card source = sa.getHostCard();
final Cost cost = sa.getPayCosts();
if (!checkConditions(ai, sa, sa.getConditions())) {
SpellAbility sub = sa.getSubAbility();
if (sub != null && !checkConditions(ai, sub, sub.getConditions())) {
return false;
}
}
if (sa.hasParam("AILogic")) {
final String logic = sa.getParam("AILogic");
final boolean alwaysOnDiscard = "AlwaysOnDiscard".equals(logic) && ai.getGame().getPhaseHandler().is(PhaseType.END_OF_TURN, ai)
&& !ai.isUnlimitedHandSize() && ai.getCardsIn(ZoneType.Hand).size() > ai.getMaxHandSize();
if (!checkAiLogic(ai, sa, logic)) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
return false;
}
if (!alwaysOnDiscard && !checkPhaseRestrictions(ai, sa, ai.getGame().getPhaseHandler(), logic)) {
return new AiAbilityDecision(0, AiPlayDecision.MissingPhaseRestrictions);
if (!checkPhaseRestrictions(ai, sa, ai.getGame().getPhaseHandler(), logic)) {
return false;
}
} else {
if (!checkPhaseRestrictions(ai, sa, ai.getGame().getPhaseHandler())) {
return false;
}
} else if (!checkPhaseRestrictions(ai, sa, ai.getGame().getPhaseHandler())) {
return new AiAbilityDecision(0, AiPlayDecision.MissingPhaseRestrictions);
} else if (ComputerUtil.preventRunAwayActivations(sa)) {
return new AiAbilityDecision(0, AiPlayDecision.StopRunawayActivations);
}
AiAbilityDecision decision = checkApiLogic(ai, sa);
if (!decision.willingToPlay()) {
return decision;
if (!checkApiLogic(ai, sa)) {
return false;
}
// needs to be after API logic because needs to check possible X Cost
// needs to be after API logic because needs to check possible X Cost?
if (cost != null && !willPayCosts(ai, sa, cost, source)) {
return new AiAbilityDecision(0, AiPlayDecision.CostNotAcceptable);
return false;
}
return true;
}
// for cards like Figure of Destiny
// (it's unlikely many valid effect would work like this -
// and while in theory AI could turn some conditions true in response that's far too advanced as default)
if (!checkConditions(ai, sa)) {
SpellAbility sub = sa.getSubAbility();
if (sub == null || !checkConditions(ai, sub)) {
return new AiAbilityDecision(0, AiPlayDecision.NeedsToPlayCriteriaNotMet);
}
}
return decision;
}
protected boolean checkConditions(final Player ai, final SpellAbility sa) {
protected boolean checkConditions(final Player ai, final SpellAbility sa, SpellAbilityCondition con) {
// copy it to disable some checks that the AI need to check extra
SpellAbilityCondition con = (SpellAbilityCondition) sa.getConditions().copy();
con = (SpellAbilityCondition) con.copy();
// if manaspent, check if AI can pay the colored mana as cost
if (!con.getManaSpent().isEmpty()) {
// need to use ManaCostBeingPaid check, can't use Cost#canPay
ManaCostBeingPaid paid = new ManaCostBeingPaid(new ManaCost(new ManaCostParser(con.getManaSpent())));
if (ComputerUtilMana.canPayManaCost(paid, sa, ai, sa.isTrigger())) {
if (ComputerUtilMana.canPayManaCost(paid, sa, ai)) {
con.setManaSpent("");
}
}
@@ -121,243 +105,17 @@ public abstract class SpellAbilityAi {
return con.areMet(sa);
}
/**
* Checks if the AI will play a SpellAbility based on its phase restrictions
*/
protected boolean checkPhaseRestrictions(final Player ai, final SpellAbility sa, final PhaseHandler ph) {
return true;
}
protected boolean checkPhaseRestrictions(final Player ai, final SpellAbility sa, final PhaseHandler ph,
final String logic) {
if (logic.equals("AtOppEOT")) {
return ph.getNextTurn() == ai && ph.is(PhaseType.END_OF_TURN);
}
return checkPhaseRestrictions(ai, sa, ph);
}
/**
* Checks if the AI will play a SpellAbility with the specified AiLogic
*/
protected boolean checkAiLogic(final Player ai, final SpellAbility sa, final String aiLogic) {
if ("Never".equals(aiLogic)) {
return false;
}
if (!"Once".equals(aiLogic)) {
return !sa.getHostCard().getAbilityActivatedThisTurn().getActivators(sa).contains(ai);
}
return true;
if (aiLogic.equals("CheckCondition")) {
SpellAbility saCopy = sa.copy();
saCopy.setActivatingPlayer(ai);
return saCopy.metConditions();
}
/**
* The rest of the logic not covered by the canPlayAI template is defined here
*/
protected AiAbilityDecision checkApiLogic(final Player ai, final SpellAbility sa) {
if (sa.getActivationsThisTurn() == 0 || MyRandom.getRandom().nextFloat() < .8f) {
// 80% chance to play the ability
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
public final boolean doTrigger(final Player aiPlayer, final SpellAbility sa, final boolean mandatory) {
// this evaluation order is currently intentional as it does more stuff that helps avoiding some crashes
if (!ComputerUtilCost.canPayCost(sa, aiPlayer, true) && !mandatory) {
return false;
}
// a mandatory SpellAbility with targeting but without candidates,
// does not need to go any deeper
if (sa.usesTargeting() && mandatory && sa.getTargetRestrictions().getNumCandidates(sa, true) == 0) {
return sa.isTargetNumberValid();
}
return doTriggerNoCostWithSubs(aiPlayer, sa, mandatory).willingToPlay();
}
public final AiAbilityDecision doTriggerNoCostWithSubs(final Player aiPlayer, final SpellAbility sa, final boolean mandatory) {
AiAbilityDecision decision = doTriggerNoCost(aiPlayer, sa, mandatory);
if (!decision.willingToPlay() && !"Always".equals(sa.getParam("AILogic"))) {
return decision;
}
final AbilitySub subAb = sa.getSubAbility();
if (subAb == null) {
if (decision.willingToPlay()) {
return decision;
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
decision = chkDrawbackWithSubs(aiPlayer, subAb);
if (decision.willingToPlay()) {
return decision;
}
if (mandatory) {
return new AiAbilityDecision(50, AiPlayDecision.MandatoryPlay);
}
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
/**
* Handles the AI decision to play a triggered SpellAbility
*/
protected AiAbilityDecision doTriggerNoCost(final Player aiPlayer, final SpellAbility sa, final boolean mandatory) {
AiAbilityDecision decision = canPlayWithoutRestrict(aiPlayer, sa);
if (decision.willingToPlay() && (!mandatory || sa.isTargetNumberValid())) {
// This is a weird check. Why do we care if its not mandatory if we WANT to do it?
return decision;
}
// not mandatory, short way out
if (!mandatory) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
// invalid target might prevent it
if (sa.usesTargeting()) {
// make list of players it does try to target
List<Player> players = Lists.newArrayList();
players.addAll(aiPlayer.getOpponents());
players.addAll(aiPlayer.getAllies());
players.add(aiPlayer);
// try to target opponent, then ally, then itself
for (final Player p : players) {
if (sa.canTarget(p)) {
sa.resetTargets();
sa.getTargets().add(p);
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
}
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
/**
* TODO: Write javadoc for this method.
* @param aiPlayer
* @param ab
* @return
*/
public AiAbilityDecision chkDrawbackWithSubs(Player aiPlayer, AbilitySub ab) {
final AbilitySub subAb = ab.getSubAbility();
AiAbilityDecision decision = SpellApiToAi.Converter.get(ab).chkDrawback(ab, aiPlayer);
if (!decision.willingToPlay()) {
return decision;
}
if (subAb == null) {
return decision;
}
return chkDrawbackWithSubs(aiPlayer, subAb);
}
/**
* Handles the AI decision to play a sub-SpellAbility
*/
public AiAbilityDecision chkDrawback(final SpellAbility sa, final Player aiPlayer) {
// sub-SpellAbility might use targets too
if (sa.usesTargeting()) {
// no Candidates, no adding to Stack
if (!sa.getTargetRestrictions().hasCandidates(sa)) {
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
}
// but if it does, it should override this function
System.err.println("Warning: default (ie. inherited from base class) implementation of chkAIDrawback is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
public boolean confirmAction(Player player, SpellAbility sa, PlayerActionConfirmMode mode, String message, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of confirmAction is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return true;
}
@SuppressWarnings("unchecked")
public <T extends GameEntity> T chooseSingleEntity(Player ai, SpellAbility sa, Collection<T> options, boolean isOptional, Player targetedPlayer, Map<String, Object> params) {
boolean hasPlayer = false;
boolean hasCard = false;
boolean hasAttackableCard = false;
for (T ent : options) {
if (ent instanceof Player) {
hasPlayer = true;
} else if (ent instanceof Card card) {
hasCard = true;
if (card.isPlaneswalker() || card.isBattle()) {
hasAttackableCard = true;
}
}
}
if (hasPlayer && hasAttackableCard) {
return (T) chooseSingleAttackableEntity(ai, sa, (Collection<GameEntity>) options, params);
} else if (hasCard) {
return (T) chooseSingleCard(ai, sa, (Collection<Card>) options, isOptional, targetedPlayer, params);
} else if (hasPlayer) {
return (T) chooseSinglePlayer(ai, sa, (Collection<Player>) options, params);
}
return null;
}
public SpellAbility chooseSingleSpellAbility(Player player, SpellAbility sa, List<SpellAbility> spells, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSingleSpellAbility is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return spells.get(0);
}
protected Card chooseSingleCard(Player ai, SpellAbility sa, Iterable<Card> options, boolean isOptional, Player targetedPlayer, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSingleCard is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(options, null);
}
protected Player chooseSinglePlayer(Player ai, SpellAbility sa, Iterable<Player> options, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSinglePlayer is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(options, null);
}
protected GameEntity chooseSingleAttackableEntity(Player ai, SpellAbility sa, Iterable<GameEntity> options, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSinglePlayerOrPlaneswalker is used for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(options, null);
}
public String chooseCardName(Player ai, SpellAbility sa, List<ICardFace> faces) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseCardName is used for " + this.getClass().getName() + ". Consider declaring an overloaded method");
final ICardFace face = Iterables.getFirst(faces, null);
return face == null ? "" : face.getName();
}
public ICardFace chooseCardFace(Player ai, SpellAbility sa, List<ICardFace> faces) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseCardFace is used for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(faces, null);
}
public CardState chooseCardState(Player ai, SpellAbility sa, List<CardState> faces, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseCardState is used for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(faces, null);
}
public int chooseNumber(Player player, SpellAbility sa, int min, int max, Map<String, Object> params) {
return max;
}
public CounterType chooseCounterType(List<CounterType> options, SpellAbility sa, Map<String, Object> params) {
return Iterables.getFirst(options, null);
}
public boolean chooseBinary(BinaryChoiceType kindOfChoice, SpellAbility sa, Map<String, Object> params) {
return MyRandom.getRandom().nextBoolean();
return !("Never".equals(aiLogic));
}
/**
@@ -381,52 +139,101 @@ public abstract class SpellAbilityAi {
return true;
}
public 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 payNever = "Never".equals(aiLogic);
boolean isMine = sa.getActivatingPlayer().equals(payer);
/**
* Checks if the AI will play a SpellAbility based on its phase restrictions
*/
protected boolean checkPhaseRestrictions(final Player ai, final SpellAbility sa, final PhaseHandler ph) {
return true;
}
if (payNever) { return false; }
protected boolean checkPhaseRestrictions(final Player ai, final SpellAbility sa, final PhaseHandler ph,
final String logic) {
return checkPhaseRestrictions(ai, sa, ph);
}
/**
* The rest of the logic not covered by the canPlayAI template is defined here
*/
protected boolean checkApiLogic(final Player ai, final SpellAbility sa) {
if (ComputerUtil.preventRunAwayActivations(sa)) {
return false; // prevent infinite loop
}
return MyRandom.getRandom().nextFloat() < .8f; // random success
}
// AI will only pay when it's not already payed and only opponents abilities
if (alreadyPaid || (payers.size() > 1 && isMine)) {
public final boolean doTriggerAI(final Player aiPlayer, final SpellAbility sa, final boolean mandatory) {
if (!ComputerUtilCost.canPayCost(sa, aiPlayer) && !mandatory) {
return false;
}
return ComputerUtilCost.checkLifeCost(payer, cost, source, 4, sa)
&& ComputerUtilCost.checkDamageCost(payer, cost, source, 4, sa)
&& (isMine || ComputerUtilCost.checkSacrificeCost(payer, cost, source, sa))
&& (isMine || ComputerUtilCost.checkDiscardCost(payer, cost, source, sa));
// a mandatory SpellAbility with targeting but without candidates,
// does not need to go any deeper
if (sa.usesTargeting() && mandatory && !sa.isTargetNumberValid()
&& !sa.getTargetRestrictions().hasCandidates(sa, true)) {
return false;
}
public List<OptionalCostValue> chooseOptionalCosts(SpellAbility chosen, Player player, List<OptionalCostValue> optionalCostValues) {
List<OptionalCostValue> chosenOptCosts = Lists.newArrayList();
Cost costSoFar = chosen.getPayCosts().copy();
return doTriggerNoCostWithSubs(aiPlayer, sa, mandatory);
}
for (OptionalCostValue opt : optionalCostValues) {
// Choose the optional cost if it can be paid (to be improved later, check for playability and other conditions perhaps)
Cost fullCost = opt.getCost().copy().add(costSoFar);
SpellAbility fullCostSa = chosen.copyWithDefinedCost(fullCost);
public final boolean doTriggerNoCostWithSubs(final Player aiPlayer, final SpellAbility sa, final boolean mandatory)
{
if (!doTriggerAINoCost(aiPlayer, sa, mandatory) && !"Always".equals(sa.getParam("AILogic"))) {
return false;
}
final AbilitySub subAb = sa.getSubAbility();
return subAb == null || chkDrawbackWithSubs(aiPlayer, subAb) || mandatory;
}
if (opt.getType() == OptionalCost.Kicker1 || opt.getType() == OptionalCost.Kicker2) {
SpellAbility kickedSaCopy = fullCostSa.copy();
kickedSaCopy.addOptionalCost(opt.getType());
Card copy = CardCopyService.getLKICopy(chosen.getHostCard());
copy.setCastSA(kickedSaCopy);
if (ComputerUtilCard.checkNeedsToPlayReqs(copy, kickedSaCopy) != AiPlayDecision.WillPlay) {
// don't choose kickers we don't want to play
continue;
/**
* Handles the AI decision to play a triggered SpellAbility
*/
protected boolean doTriggerAINoCost(final Player aiPlayer, final SpellAbility sa, final boolean mandatory) {
if (canPlayWithoutRestrict(aiPlayer, sa)) {
return true;
}
// not mandatory, short way out
if (!mandatory) {
return false;
}
// invalid target might prevent it
if (sa.usesTargeting()) {
// make list of players it does try to target
List<Player> players = Lists.newArrayList();
players.addAll(aiPlayer.getOpponents());
players.addAll(aiPlayer.getAllies());
players.add(aiPlayer);
// try to target opponent, then ally, then itself
for (final Player p : players) {
if (p.canBeTargetedBy(sa) && sa.canTarget(p)) {
sa.resetTargets();
sa.getTargets().add(p);
return true;
}
}
if (ComputerUtilCost.canPayCost(fullCostSa, player, false)) {
chosenOptCosts.add(opt);
costSoFar.add(opt.getCost());
return false;
}
return true;
}
return chosenOptCosts;
/**
* Handles the AI decision to play a sub-SpellAbility
*/
public boolean chkAIDrawback(final SpellAbility sa, final Player aiPlayer) {
// sub-SpellAbility might use targets too
if (sa.usesTargeting()) {
// no Candidates, no adding to Stack
if (!sa.getTargetRestrictions().hasCandidates(sa, true)) {
return false;
}
// but if it does, it should override this function
System.err.println("Warning: default (ie. inherited from base class) implementation of chkAIDrawback is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return false;
}
return true;
}
/**
@@ -438,11 +245,11 @@ public abstract class SpellAbilityAi {
* a {@link forge.game.spellability.SpellAbility} object.
* @return a boolean.
*/
protected static boolean isSorcerySpeed(final SpellAbility sa, Player ai) {
protected static boolean isSorcerySpeed(final SpellAbility sa) {
return (sa.getRootAbility().isSpell() && sa.getHostCard().isSorcery())
|| (sa.getRootAbility().isActivatedAbility() && sa.getRootAbility().getRestrictions().isSorcerySpeed())
|| (sa.getRootAbility().isAdventure() && sa.getHostCard().getState(CardStateName.Secondary).getType().isSorcery())
|| (sa.isPwAbility() && !sa.withFlash(sa.getHostCard(), ai));
|| (sa.getRootAbility().isAbility() && sa.getRestrictions().isSorcerySpeed())
|| (sa.getRootAbility().isAdventure() && sa.getHostCard().getState(CardStateName.Adventure).getType().isSorcery())
|| (sa.isPwAbility() && !sa.getHostCard().hasKeyword("CARDNAME's loyalty abilities can be activated at instant speed."));
}
/**
@@ -474,10 +281,94 @@ public abstract class SpellAbilityAi {
if (sa.isPwAbility() && phase.is(PhaseType.MAIN2)) {
return true;
}
if (sa.isSpell() && !sa.isBuyback()) {
if (sa.isSpell() && !sa.isBuyBackAbility()) {
return false;
}
return phase.is(PhaseType.END_OF_TURN) && phase.getNextTurn().equals(ai);
}
/**
* TODO: Write javadoc for this method.
* @param aiPlayer
* @param ab
* @return
*/
public boolean chkDrawbackWithSubs(Player aiPlayer, AbilitySub ab) {
final AbilitySub subAb = ab.getSubAbility();
return SpellApiToAi.Converter.get(ab.getApi()).chkAIDrawback(ab, aiPlayer) && (subAb == null || chkDrawbackWithSubs(aiPlayer, subAb));
}
public boolean confirmAction(Player player, SpellAbility sa, PlayerActionConfirmMode mode, String message) {
System.err.println("Warning: default (ie. inherited from base class) implementation of confirmAction is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return true;
}
@SuppressWarnings("unchecked")
public <T extends GameEntity> T chooseSingleEntity(Player ai, SpellAbility sa, Collection<T> options, boolean isOptional, Player targetedPlayer, Map<String, Object> params) {
boolean hasPlayer = false;
boolean hasCard = false;
boolean hasPlaneswalker = false;
for (T ent : options) {
if (ent instanceof Player) {
hasPlayer = true;
} else if (ent instanceof Card) {
hasCard = true;
if (((Card)ent).isPlaneswalker()) {
hasPlaneswalker = true;
}
}
}
if (hasPlayer && hasPlaneswalker) {
return (T) chooseSinglePlayerOrPlaneswalker(ai, sa, (Collection<GameEntity>) options, params);
} else if (hasCard) {
return (T) chooseSingleCard(ai, sa, (Collection<Card>) options, isOptional, targetedPlayer, params);
} else if (hasPlayer) {
return (T) chooseSinglePlayer(ai, sa, (Collection<Player>) options, params);
}
return null;
}
public SpellAbility chooseSingleSpellAbility(Player player, SpellAbility sa, List<SpellAbility> spells, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSingleSpellAbility is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return spells.get(0);
}
protected Card chooseSingleCard(Player ai, SpellAbility sa, Iterable<Card> options, boolean isOptional, Player targetedPlayer, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSingleCard is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(options, null);
}
protected Player chooseSinglePlayer(Player ai, SpellAbility sa, Iterable<Player> options, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSinglePlayer is used by " + sa.getHostCard().getName() + " for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(options, null);
}
protected GameEntity chooseSinglePlayerOrPlaneswalker(Player ai, SpellAbility sa, Iterable<GameEntity> options, Map<String, Object> params) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseSinglePlayerOrPlaneswalker is used for " + this.getClass().getName() + ". Consider declaring an overloaded method");
return Iterables.getFirst(options, null);
}
public String chooseCardName(Player ai, SpellAbility sa, List<ICardFace> faces) {
System.err.println("Warning: default (ie. inherited from base class) implementation of chooseCardName is used for " + this.getClass().getName() + ". Consider declaring an overloaded method");
final ICardFace face = Iterables.getFirst(faces, null);
return face == null ? "" : face.getName();
}
public int chooseNumber(Player player, SpellAbility sa, int min, int max, Map<String, Object> params) {
return max;
}
public CounterType chooseCounterType(List<CounterType> options, SpellAbility sa, Map<String, Object> params) {
return Iterables.getFirst(options, null);
}
public boolean chooseBinary(BinaryChoiceType kindOfChoice, SpellAbility sa, Map<String, Object> params) {
return MyRandom.getRandom().nextBoolean();
}
}

View File

@@ -1,15 +1,14 @@
package forge.ai;
import java.util.Map;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import forge.ai.ability.*;
import forge.game.ability.ApiType;
import forge.game.spellability.SpellAbility;
import forge.util.ReflectionUtil;
import java.security.InvalidParameterException;
import java.util.Map;
public enum SpellApiToAi {
Converter;
@@ -23,30 +22,23 @@ public enum SpellApiToAi {
.put(ApiType.AddOrRemoveCounter, CountersPutOrRemoveAi.class)
.put(ApiType.AddPhase, AddPhaseAi.class)
.put(ApiType.AddTurn, AddTurnAi.class)
.put(ApiType.AdvanceCrank, AdvanceCrankAi.class)
.put(ApiType.AlterAttribute, AlterAttributeAi.class)
.put(ApiType.Amass, AmassAi.class)
.put(ApiType.Animate, AnimateAi.class)
.put(ApiType.AnimateAll, AnimateAllAi.class)
.put(ApiType.Attach, AttachAi.class)
.put(ApiType.Ascend, AlwaysPlayAi.class)
.put(ApiType.AssembleContraption, AssembleContraptionAi.class)
.put(ApiType.AssignGroup, AssignGroupAi.class)
.put(ApiType.Balance, BalanceAi.class)
.put(ApiType.BecomeMonarch, AlwaysPlayAi.class)
.put(ApiType.BecomesBlocked, BecomesBlockedAi.class)
.put(ApiType.BidLife, BidLifeAi.class)
.put(ApiType.BlankLine, AlwaysPlayAi.class)
.put(ApiType.Bond, BondAi.class)
.put(ApiType.Branch, BranchAi.class)
.put(ApiType.Camouflage, ChooseCardAi.class)
.put(ApiType.Branch, AlwaysPlayAi.class)
.put(ApiType.ChangeCombatants, ChangeCombatantsAi.class)
.put(ApiType.ChangeSpeed, AlwaysPlayAi.class)
.put(ApiType.ChangeTargets, ChangeTargetsAi.class)
.put(ApiType.ChangeX, AlwaysPlayAi.class)
.put(ApiType.ChangeZone, ChangeZoneAi.class)
.put(ApiType.ChangeZoneAll, ChangeZoneAllAi.class)
.put(ApiType.ChaosEnsues, AlwaysPlayAi.class)
.put(ApiType.Charm, CharmAi.class)
.put(ApiType.ChooseCard, ChooseCardAi.class)
.put(ApiType.ChooseColor, ChooseColorAi.class)
@@ -54,26 +46,20 @@ public enum SpellApiToAi {
.put(ApiType.ChooseEvenOdd, ChooseEvenOddAi.class)
.put(ApiType.ChooseNumber, ChooseNumberAi.class)
.put(ApiType.ChoosePlayer, ChoosePlayerAi.class)
.put(ApiType.ChooseSector, AlwaysPlayAi.class)
.put(ApiType.ChooseSource, ChooseSourceAi.class)
.put(ApiType.ChooseType, ChooseTypeAi.class)
.put(ApiType.ClaimThePrize, AlwaysPlayAi.class)
.put(ApiType.Clash, ClashAi.class)
.put(ApiType.ClassLevelUp, ClassLevelUpAi.class)
.put(ApiType.Cleanup, AlwaysPlayAi.class)
.put(ApiType.Cloak, CloakAi.class)
.put(ApiType.Clone, CloneAi.class)
.put(ApiType.CompanionChoose, ChooseCompanionAi.class)
.put(ApiType.Connive, ConniveAi.class)
.put(ApiType.CopyPermanent, CopyPermanentAi.class)
.put(ApiType.CopySpellAbility, CopySpellAbilityAi.class)
.put(ApiType.ControlPlayer, CannotPlayAi.class)
.put(ApiType.ControlSpell, CannotPlayAi.class)
.put(ApiType.Counter, CounterAi.class)
.put(ApiType.DamageAll, DamageAllAi.class)
.put(ApiType.DayTime, DayTimeAi.class)
.put(ApiType.DealDamage, DamageDealAi.class)
.put(ApiType.Debuff, DebuffAi.class)
.put(ApiType.DeclareCombatants, CannotPlayAi.class)
.put(ApiType.DelayedTrigger, DelayedTriggerAi.class)
.put(ApiType.Destroy, DestroyAi.class)
.put(ApiType.DestroyAll, DestroyAllAi.class)
@@ -81,14 +67,11 @@ public enum SpellApiToAi {
.put(ApiType.DigMultiple, DigMultipleAi.class)
.put(ApiType.DigUntil, DigUntilAi.class)
.put(ApiType.Discard, DiscardAi.class)
.put(ApiType.Discover, DiscoverAi.class)
.put(ApiType.Draft, ChooseCardNameAi.class)
.put(ApiType.DrainMana, DrainManaAi.class)
.put(ApiType.Draw, DrawAi.class)
.put(ApiType.EachDamage, DamageEachAi.class)
.put(ApiType.Effect, EffectAi.class)
.put(ApiType.Encode, EncodeAi.class)
.put(ApiType.Endure, EndureAi.class)
.put(ApiType.EndCombatPhase, EndTurnAi.class)
.put(ApiType.EndTurn, EndTurnAi.class)
.put(ApiType.ExchangeLife, LifeExchangeAi.class)
@@ -100,38 +83,32 @@ public enum SpellApiToAi {
.put(ApiType.Explore, ExploreAi.class)
.put(ApiType.Fight, FightAi.class)
.put(ApiType.FlipACoin, FlipACoinAi.class)
.put(ApiType.FlipOntoBattlefield, FlipOntoBattlefieldAi.class)
.put(ApiType.Fog, FogAi.class)
.put(ApiType.GainControl, ControlGainAi.class)
.put(ApiType.GainControlVariant, ControlGainVariantAi.class)
.put(ApiType.GainLife, LifeGainAi.class)
.put(ApiType.GainOwnership, CannotPlayAi.class)
.put(ApiType.GameDrawn, CannotPlayAi.class)
.put(ApiType.GenericChoice, ChooseGenericAi.class)
.put(ApiType.GenericChoice, ChooseGenericEffectAi.class)
.put(ApiType.Goad, GoadAi.class)
.put(ApiType.Heist, AlwaysPlayAi.class)
.put(ApiType.Haunt, HauntAi.class)
.put(ApiType.ImmediateTrigger, ImmediateTriggerAi.class)
.put(ApiType.Investigate, InvestigateAi.class)
.put(ApiType.Learn, LearnAi.class)
.put(ApiType.LoseLife, LifeLoseAi.class)
.put(ApiType.LosePerpetual, AlwaysPlayAi.class)
.put(ApiType.LosesGame, GameLossAi.class)
.put(ApiType.MakeCard, AlwaysPlayAi.class)
.put(ApiType.Mana, ManaAi.class)
.put(ApiType.Mana, ManaEffectAi.class)
.put(ApiType.ManaReflected, CannotPlayAi.class)
.put(ApiType.Manifest, ManifestAi.class)
.put(ApiType.ManifestDread, ManifestAi.class)
.put(ApiType.Meld, MeldAi.class)
.put(ApiType.Mill, MillAi.class)
.put(ApiType.MoveCounter, CountersMoveAi.class)
.put(ApiType.MultiplePiles, CannotPlayAi.class)
.put(ApiType.MultiplyCounter, CountersMultiplyAi.class)
.put(ApiType.MustAttack, MustAttackAi.class)
.put(ApiType.MustBlock, MustBlockAi.class)
.put(ApiType.Mutate, MutateAi.class)
.put(ApiType.NameCard, ChooseCardNameAi.class)
//.put(ApiType.NoteCounters, AlwaysPlayAi.class)
.put(ApiType.OpenAttraction, AssembleContraptionAi.class)
.put(ApiType.NoteCounters, AlwaysPlayAi.class)
.put(ApiType.PeekAndReveal, PeekAndRevealAi.class)
.put(ApiType.PermanentCreature, PermanentCreatureAi.class)
.put(ApiType.PermanentNoncreature, PermanentNoncreatureAi.class)
@@ -141,6 +118,7 @@ public enum SpellApiToAi {
.put(ApiType.PlayLandVariant, CannotPlayAi.class)
.put(ApiType.Poison, PoisonAi.class)
.put(ApiType.PreventDamage, DamagePreventAi.class)
.put(ApiType.PreventDamageAll, DamagePreventAllAi.class)
.put(ApiType.Proliferate, CountersProliferateAi.class)
.put(ApiType.Protection, ProtectAi.class)
.put(ApiType.ProtectionAll, ProtectAllAi.class)
@@ -148,36 +126,29 @@ public enum SpellApiToAi {
.put(ApiType.PumpAll, PumpAllAi.class)
.put(ApiType.PutCounter, CountersPutAi.class)
.put(ApiType.PutCounterAll, CountersPutAllAi.class)
.put(ApiType.Radiation, AlwaysPlayAi.class)
.put(ApiType.RearrangeTopOfLibrary, RearrangeTopOfLibraryAi.class)
.put(ApiType.Regenerate, RegenerateAi.class)
.put(ApiType.RegenerateAll, RegenerateAllAi.class)
.put(ApiType.Regeneration, AlwaysPlayAi.class)
.put(ApiType.RemoveCounter, CountersRemoveAi.class)
.put(ApiType.RemoveCounterAll, CannotPlayAi.class)
.put(ApiType.RemoveFromCombat, RemoveFromCombatAi.class)
.put(ApiType.RemoveFromGame, AlwaysPlayAi.class)
.put(ApiType.RemoveFromMatch, AlwaysPlayAi.class)
.put(ApiType.ReorderZone, AlwaysPlayAi.class)
.put(ApiType.Repeat, RepeatAi.class)
.put(ApiType.RepeatEach, RepeatEachAi.class)
.put(ApiType.ReplaceCounter, AlwaysPlayAi.class)
.put(ApiType.ReplaceEffect, AlwaysPlayAi.class)
.put(ApiType.ReplaceDamage, ReplaceDamageAi.class)
.put(ApiType.ReplaceMana, AlwaysPlayAi.class)
.put(ApiType.ReplaceSplitDamage, ReplaceDamageAi.class)
.put(ApiType.ReplaceToken, AlwaysPlayAi.class)
.put(ApiType.ReplaceDamage, AlwaysPlayAi.class)
.put(ApiType.ReplaceSplitDamage, AlwaysPlayAi.class)
.put(ApiType.RestartGame, RestartGameAi.class)
.put(ApiType.Reveal, RevealAi.class)
.put(ApiType.RevealHand, RevealHandAi.class)
.put(ApiType.ReverseTurnOrder, AlwaysPlayAi.class)
.put(ApiType.RingTemptsYou, AlwaysPlayAi.class)
.put(ApiType.RollDice, RollDiceAi.class)
.put(ApiType.RollPlanarDice, RollPlanarDiceAi.class)
.put(ApiType.RunChaos, AlwaysPlayAi.class)
.put(ApiType.Sacrifice, SacrificeAi.class)
.put(ApiType.SacrificeAll, SacrificeAllAi.class)
.put(ApiType.Scry, ScryAi.class)
.put(ApiType.Seek, AlwaysPlayAi.class)
.put(ApiType.SetInMotion, AlwaysPlayAi.class)
.put(ApiType.SetLife, LifeSetAi.class)
.put(ApiType.SetState, SetStateAi.class)
@@ -187,38 +158,25 @@ public enum SpellApiToAi {
.put(ApiType.StoreSVar, StoreSVarAi.class)
.put(ApiType.Subgame, AlwaysPlayAi.class)
.put(ApiType.Surveil, SurveilAi.class)
.put(ApiType.TakeInitiative, AlwaysPlayAi.class)
.put(ApiType.Tap, TapAi.class)
.put(ApiType.TapAll, TapAllAi.class)
.put(ApiType.TapOrUntap, TapOrUntapAi.class)
.put(ApiType.TapOrUntapAll, TapOrUntapAllAi.class)
.put(ApiType.TimeTravel, TimeTravelAi.class)
.put(ApiType.Token, TokenAi.class)
.put(ApiType.TwoPiles, TwoPilesAi.class)
.put(ApiType.Unattach, CannotPlayAi.class)
.put(ApiType.UnattachAll, UnattachAllAi.class)
.put(ApiType.UnlockDoor, AlwaysPlayAi.class)
.put(ApiType.Untap, UntapAi.class)
.put(ApiType.UntapAll, UntapAllAi.class)
.put(ApiType.Venture, VentureAi.class)
.put(ApiType.VillainousChoice, AlwaysPlayAi.class)
.put(ApiType.Vote, VoteAi.class)
.put(ApiType.WinsGame, GameWinAi.class)
.put(ApiType.DamageResolve, AlwaysPlayAi.class)
.put(ApiType.InternalEtbReplacement, CanPlayAsDrawbackAi.class)
.put(ApiType.InternalLegendaryRule, LegendaryRuleAi.class)
.put(ApiType.InternalIgnoreEffect, CannotPlayAi.class)
.put(ApiType.InternalRadiation, AlwaysPlayAi.class)
.build());
public SpellAbilityAi get(final SpellAbility sa) {
ApiType api = sa.getApi();
if (null == api) {
throw new InvalidParameterException("SA is not api-based, this is not supported yet");
}
return get(api);
}
public SpellAbilityAi get(final ApiType api) {
SpellAbilityAi result = apiToInstance.get(api);
if (null == result) {

View File

@@ -1,7 +1,8 @@
package forge.ai.ability;
import forge.ai.AiAbilityDecision;
import forge.ai.AiPlayDecision;
import java.util.List;
import java.util.Map;
import forge.ai.SpellAbilityAi;
import forge.game.ability.AbilityUtils;
import forge.game.card.Card;
@@ -10,76 +11,82 @@ import forge.game.player.Player;
import forge.game.spellability.SpellAbility;
import forge.game.spellability.TargetRestrictions;
import forge.game.zone.ZoneType;
import java.util.List;
import java.util.Map;
import forge.util.MyRandom;
public class ActivateAbilityAi extends SpellAbilityAi {
@Override
protected AiAbilityDecision checkApiLogic(Player ai, SpellAbility sa) {
protected boolean canPlayAI(Player ai, SpellAbility sa) {
// AI cannot use this properly until he can use SAs during Humans turn
final TargetRestrictions tgt = sa.getTargetRestrictions();
final Card source = sa.getHostCard();
final Player opp = ai.getStrongestOpponent();
final Player opp = ai.getWeakestOpponent();
boolean randomReturn = MyRandom.getRandom().nextFloat() <= Math.pow(.6667, sa.getActivationsThisTurn());
List<Card> list = CardLists.getType(opp.getCardsIn(ZoneType.Battlefield), sa.getParamOrDefault("Type", "Card"));
if (list.isEmpty()) {
return new AiAbilityDecision(0, AiPlayDecision.MissingNeededCards);
return false;
}
if (!sa.usesTargeting()) {
if (tgt == null) {
final List<Player> defined = AbilityUtils.getDefinedPlayers(source, sa.getParam("Defined"), sa);
if (!defined.contains(opp)) {
return new AiAbilityDecision(0, AiPlayDecision.MissingNeededCards);
return false;
}
} else {
sa.resetTargets();
if (sa.canTarget(opp)) {
sa.getTargets().add(opp);
} else {
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
}
}
return super.checkApiLogic(ai, sa);
return randomReturn;
}
@Override
protected AiAbilityDecision doTriggerNoCost(Player ai, SpellAbility sa, boolean mandatory) {
final Player opp = ai.getStrongestOpponent();
protected boolean doTriggerAINoCost(Player ai, SpellAbility sa, boolean mandatory) {
final Player opp = ai.getWeakestOpponent();
final TargetRestrictions tgt = sa.getTargetRestrictions();
final Card source = sa.getHostCard();
if (null == tgt) {
if (mandatory) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return true;
} else {
final List<Player> defined = AbilityUtils.getDefinedPlayers(source, sa.getParam("Defined"), sa);
if (defined.contains(opp)) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
} else {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
return defined.contains(opp);
}
} else {
sa.resetTargets();
sa.getTargets().add(opp);
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return true;
}
@Override
public AiAbilityDecision chkDrawback(SpellAbility sa, Player ai) {
public boolean chkAIDrawback(SpellAbility sa, Player ai) {
// AI cannot use this properly until he can use SAs during Humans turn
final TargetRestrictions tgt = sa.getTargetRestrictions();
final Card source = sa.getHostCard();
if (!sa.usesTargeting()) {
boolean randomReturn = true;
if (tgt == null) {
final List<Player> defined = AbilityUtils.getDefinedPlayers(source, sa.getParam("Defined"), sa);
if (defined.contains(ai)) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
return false;
}
} else {
sa.resetTargets();
sa.getTargets().add(ai.getWeakestOpponent());
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return randomReturn;
}
@Override

View File

@@ -1,7 +1,5 @@
package forge.ai.ability;
import forge.ai.AiAbilityDecision;
import forge.ai.AiPlayDecision;
import forge.ai.SpellAbilityAi;
import forge.game.player.Player;
import forge.game.spellability.SpellAbility;
@@ -13,8 +11,8 @@ import forge.game.spellability.SpellAbility;
public class AddPhaseAi extends SpellAbilityAi {
@Override
protected AiAbilityDecision canPlay(Player aiPlayer, SpellAbility sa) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
protected boolean canPlayAI(Player aiPlayer, SpellAbility sa) {
return false;
}
}

View File

@@ -17,17 +17,14 @@
*/
package forge.ai.ability;
import forge.ai.AiAbilityDecision;
import forge.ai.AiPlayDecision;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import forge.ai.SpellAbilityAi;
import forge.game.ability.AbilityUtils;
import forge.game.player.Player;
import forge.game.player.PlayerCollection;
import forge.game.player.PlayerPredicates;
import forge.game.spellability.SpellAbility;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
/**
* <p>
@@ -39,14 +36,14 @@ import java.util.List;
*/
public class AddTurnAi extends SpellAbilityAi {
@Override
protected AiAbilityDecision doTriggerNoCost(Player ai, SpellAbility sa, boolean mandatory) {
PlayerCollection targetableOpps = ai.getOpponents().filter(PlayerPredicates.isTargetableBy(sa));
Player opp = targetableOpps.min(PlayerPredicates.compareByLife());
protected boolean doTriggerAINoCost(Player ai, SpellAbility sa, boolean mandatory) {
final Player opp = ai.getWeakestOpponent();
if (sa.usesTargeting()) {
sa.resetTargets();
if (sa.canTarget(ai) && (mandatory || !ai.getGame().getReplacementHandler().wouldExtraTurnBeSkipped(ai))) {
if (sa.canTarget(ai)) {
sa.getTargets().add(ai);
} else if (mandatory) {
for (final Player ally : ai.getAllies()) {
@@ -55,35 +52,35 @@ public class AddTurnAi extends SpellAbilityAi {
break;
}
}
if (!sa.getTargetRestrictions().isMinTargetsChosen(sa.getHostCard(), sa) && opp != null) {
if (!sa.getTargetRestrictions().isMinTargetsChosen(sa.getHostCard(), sa) && sa.canTarget(opp)) {
sa.getTargets().add(opp);
} else {
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
return false;
}
} else {
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
return false;
}
} else {
final List<Player> tgtPlayers = AbilityUtils.getDefinedPlayers(sa.getHostCard(), sa.getParam("Defined"), sa);
for (final Player p : tgtPlayers) {
if (p.isOpponentOf(ai) && !mandatory) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
return false;
}
}
// TODO: improve ai for Sage of Hours
if (!StringUtils.isNumeric(sa.getParam("NumTurns"))) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
return StringUtils.isNumeric(sa.getParam("NumTurns"));
// not sure if the AI should be playing with cards that give the
// Human more turns.
}
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
return true;
}
/* (non-Javadoc)
* @see forge.card.abilityfactory.SpellAiLogic#canPlayAI(forge.game.player.Player, java.util.Map, forge.card.spellability.SpellAbility)
*/
@Override
protected AiAbilityDecision canPlay(Player aiPlayer, SpellAbility sa) {
return doTriggerNoCost(aiPlayer, sa, false);
protected boolean canPlayAI(Player aiPlayer, SpellAbility sa) {
return doTriggerAINoCost(aiPlayer, sa, false);
}
}

View File

@@ -1,23 +0,0 @@
package forge.ai.ability;
import forge.ai.AiAbilityDecision;
import forge.ai.AiPlayDecision;
import forge.ai.SpellAbilityAi;
import forge.game.card.CardLists;
import forge.game.card.CardPredicates;
import forge.game.player.Player;
import forge.game.spellability.SpellAbility;
import forge.game.zone.ZoneType;
public class AdvanceCrankAi extends SpellAbilityAi {
@Override
protected AiAbilityDecision canPlay(Player ai, SpellAbility sa) {
int nextSprocket = (ai.getCrankCounter() % 3) + 1;
int crankCount = CardLists.count(ai.getCardsIn(ZoneType.Battlefield), CardPredicates.isContraptionOnSprocket(nextSprocket));
if (crankCount < 2) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
return super.canPlay(ai, sa);
}
}

View File

@@ -1,109 +0,0 @@
package forge.ai.ability;
import forge.ai.AiAbilityDecision;
import forge.ai.AiPlayDecision;
import forge.ai.SpellAbilityAi;
import forge.game.ability.AbilityUtils;
import forge.game.card.Card;
import forge.game.combat.CombatUtil;
import forge.game.phase.PhaseHandler;
import forge.game.phase.PhaseType;
import forge.game.player.Player;
import forge.game.player.PlayerActionConfirmMode;
import forge.game.spellability.SpellAbility;
import java.util.List;
import java.util.Map;
public class AlterAttributeAi extends SpellAbilityAi {
@Override
protected AiAbilityDecision checkApiLogic(Player aiPlayer, SpellAbility sa) {
final Card source = sa.getHostCard();
boolean activate = Boolean.parseBoolean(sa.getParamOrDefault("Activate", "true"));
String[] attributes = sa.getParam("Attributes").split(",");
if (sa.usesTargeting()) {
// TODO add targeting logic
// needed for Suspected
return new AiAbilityDecision(0, AiPlayDecision.TargetingFailed);
}
final List<Card> defined = AbilityUtils.getDefinedCards(source, sa.getParam("Defined"), sa);
for (Card c : defined) {
for (String attr : attributes) {
switch (attr.trim()) {
case "Solve":
case "Solved":
// there is currently no effect that would un-solve something
if (!c.isSolved() && activate) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
break;
case "Suspect":
case "Suspected":
// is Suspected good or bad?
// currently Suspected is better
if (!activate) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
case "Saddle":
case "Saddled":
// AI should not try to Saddle again?
if (c.isSaddled()) {
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
}
}
}
return new AiAbilityDecision(0, AiPlayDecision.CantPlayAi);
}
@Override
protected boolean checkPhaseRestrictions(final Player ai, final SpellAbility sa, final PhaseHandler ph) {
final Card source = sa.getHostCard();
String[] attributes = sa.getParam("Attributes").split(",");
// currently Phase is only checked for Saddled
for (String attr : attributes) {
switch (attr.trim()) {
case "Saddle":
case "Saddled":
if (!ph.isPlayerTurn(ai)) {
return false;
}
// it is too late for combat, Saddle is Sorcery Speed
if (!ph.getPhase().isBefore(PhaseType.COMBAT_BEGIN)) {
return false;
}
// would card attack?
if (!CombatUtil.canAttack(source)) {
return false;
}
}
}
return true;
}
@Override
public boolean confirmAction(Player player, SpellAbility sa, PlayerActionConfirmMode mode, String message, Map<String, Object> params) {
boolean activate = Boolean.parseBoolean(sa.getParamOrDefault("Activate", "true"));
String[] attributes = sa.getParam("Attributes").split(",");
for (String attr : attributes) {
switch (attr.trim()) {
case "Suspect":
case "Suspected":
return activate;
}
}
return true;
}
}

View File

@@ -1,25 +1,22 @@
package forge.ai.ability;
import forge.ai.AiAbilityDecision;
import forge.ai.AiPlayDecision;
import forge.ai.SpellAbilityAi;
import forge.game.player.Player;
import forge.game.player.PlayerActionConfirmMode;
import forge.game.spellability.SpellAbility;
import java.util.Map;
public class AlwaysPlayAi extends SpellAbilityAi {
/* (non-Javadoc)
* @see forge.card.abilityfactory.SpellAiLogic#canPlayAI(forge.game.player.Player, java.util.Map, forge.card.spellability.SpellAbility)
*/
@Override
protected AiAbilityDecision canPlay(Player aiPlayer, SpellAbility sa) {
return new AiAbilityDecision(100, AiPlayDecision.WillPlay);
protected boolean canPlayAI(Player aiPlayer, SpellAbility sa) {
return true;
}
@Override
public boolean confirmAction(Player player, SpellAbility sa, PlayerActionConfirmMode mode, String message, Map<String, Object> params) {
public boolean confirmAction(Player player, SpellAbility sa, PlayerActionConfirmMode mode, String message) {
return true;
}
}

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