Initial commit

This commit is contained in:
jjayers99
2023-06-30 22:30:54 -04:00
commit d9c0a08662
38719 changed files with 1599809 additions and 0 deletions

13
.checkstyle Normal file
View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
<local-check-config name="Forge Checkstyle Config" location="src/main/config/forge_checks.xml" type="project" description="">
<property name="cacheFile" value="/target/checkstyle-cachefile"/>
<additional-data name="protect-config-file" value="false"/>
</local-check-config>
<fileset name="all" enabled="true" check-config-name="Forge Checkstyle Config" local="true">
<file-match-pattern match-pattern="." include-pattern="true"/>
</fileset>
<filter name="WriteProtectedFiles" enabled="true"/>
<filter name="UnOpenedFiles" enabled="true"/>
</fileset-config>

127
.fbprefs Normal file
View File

@@ -0,0 +1,127 @@
#FindBugs User Preferences
#Wed Jul 27 18:41:56 EDT 2011
detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true
detectorBadAppletConstructor=BadAppletConstructor|false
detectorBadResultSetAccess=BadResultSetAccess|true
detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true
detectorBadUseOfReturnValue=BadUseOfReturnValue|true
detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true
detectorBooleanReturnNull=BooleanReturnNull|true
detectorCallToUnsupportedMethod=CallToUnsupportedMethod|false
detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true
detectorCheckTypeQualifiers=CheckTypeQualifiers|true
detectorCloneIdiom=CloneIdiom|true
detectorComparatorIdiom=ComparatorIdiom|true
detectorConfusedInheritance=ConfusedInheritance|true
detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true
detectorCrossSiteScripting=CrossSiteScripting|true
detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true
detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true
detectorDontIgnoreResultOfPutIfAbsent=DontIgnoreResultOfPutIfAbsent|true
detectorDontUseEnum=DontUseEnum|true
detectorDroppedException=DroppedException|true
detectorDumbMethodInvocations=DumbMethodInvocations|true
detectorDumbMethods=DumbMethods|true
detectorDuplicateBranches=DuplicateBranches|true
detectorEmptyZipFileEntry=EmptyZipFileEntry|true
detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true
detectorFinalizerNullsFields=FinalizerNullsFields|true
detectorFindBadCast2=FindBadCast2|true
detectorFindBadForLoop=FindBadForLoop|true
detectorFindCircularDependencies=FindCircularDependencies|false
detectorFindDeadLocalStores=FindDeadLocalStores|true
detectorFindDoubleCheck=FindDoubleCheck|true
detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true
detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true
detectorFindFinalizeInvocations=FindFinalizeInvocations|true
detectorFindFloatEquality=FindFloatEquality|true
detectorFindHEmismatch=FindHEmismatch|true
detectorFindInconsistentSync2=FindInconsistentSync2|true
detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true
detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true
detectorFindMaskedFields=FindMaskedFields|true
detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true
detectorFindNakedNotify=FindNakedNotify|true
detectorFindNonSerializableStoreIntoSession=FindNonSerializableStoreIntoSession|true
detectorFindNonSerializableValuePassedToWriteObject=FindNonSerializableValuePassedToWriteObject|true
detectorFindNonShortCircuit=FindNonShortCircuit|true
detectorFindNullDeref=FindNullDeref|true
detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true
detectorFindOpenStream=FindOpenStream|true
detectorFindPuzzlers=FindPuzzlers|true
detectorFindRefComparison=FindRefComparison|true
detectorFindReturnRef=FindReturnRef|true
detectorFindRunInvocations=FindRunInvocations|true
detectorFindSelfComparison=FindSelfComparison|true
detectorFindSelfComparison2=FindSelfComparison2|true
detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true
detectorFindSpinLoop=FindSpinLoop|true
detectorFindSqlInjection=FindSqlInjection|true
detectorFindTwoLockWait=FindTwoLockWait|true
detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true
detectorFindUnconditionalWait=FindUnconditionalWait|true
detectorFindUninitializedGet=FindUninitializedGet|true
detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true
detectorFindUnreleasedLock=FindUnreleasedLock|true
detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true
detectorFindUnsyncGet=FindUnsyncGet|true
detectorFindUselessControlFlow=FindUselessControlFlow|true
detectorFormatStringChecker=FormatStringChecker|true
detectorHugeSharedStringConstants=HugeSharedStringConstants|true
detectorIDivResultCastToDouble=IDivResultCastToDouble|true
detectorIncompatMask=IncompatMask|true
detectorInconsistentAnnotations=InconsistentAnnotations|true
detectorInefficientMemberAccess=InefficientMemberAccess|false
detectorInefficientToArray=InefficientToArray|true
detectorInfiniteLoop=InfiniteLoop|true
detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true
detectorInfiniteRecursiveLoop2=InfiniteRecursiveLoop2|false
detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true
detectorInitializationChain=InitializationChain|true
detectorInstantiateStaticClass=InstantiateStaticClass|true
detectorInvalidJUnitTest=InvalidJUnitTest|true
detectorIteratorIdioms=IteratorIdioms|true
detectorLazyInit=LazyInit|true
detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true
detectorLostLoggerDueToWeakReference=LostLoggerDueToWeakReference|true
detectorMethodReturnCheck=MethodReturnCheck|true
detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true
detectorMutableLock=MutableLock|true
detectorMutableStaticFields=MutableStaticFields|true
detectorNaming=Naming|true
detectorNumberConstructor=NumberConstructor|true
detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true
detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true
detectorPublicSemaphores=PublicSemaphores|false
detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true
detectorReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass=ReadOfInstanceFieldInMethodInvokedByConstructorInSuperclass|true
detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true
detectorRedundantInterfaces=RedundantInterfaces|true
detectorRepeatedConditionals=RepeatedConditionals|true
detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true
detectorSerializableIdiom=SerializableIdiom|true
detectorStartInConstructor=StartInConstructor|true
detectorStaticCalendarDetector=StaticCalendarDetector|true
detectorStringConcatenation=StringConcatenation|true
detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true
detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true
detectorSwitchFallthrough=SwitchFallthrough|true
detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true
detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true
detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true
detectorURLProblems=URLProblems|true
detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true
detectorUnnecessaryMath=UnnecessaryMath|true
detectorUnreadFields=UnreadFields|true
detectorUseObjectEquals=UseObjectEquals|false
detectorUselessSubclassMethod=UselessSubclassMethod|false
detectorVarArgsProblems=VarArgsProblems|true
detectorVolatileUsage=VolatileUsage|true
detectorWaitInLoop=WaitInLoop|true
detectorWrongMapIterator=WrongMapIterator|true
detectorXMLFactoryBypass=XMLFactoryBypass|true
detector_threshold=2
effort=default
filter_settings=Medium|BAD_PRACTICE,CORRECTNESS,MT_CORRECTNESS,PERFORMANCE,STYLE|false
filter_settings_neg=MALICIOUS_CODE,NOISE,I18N,SECURITY,EXPERIMENTAL|
run_at_full_build=false

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
* text=auto

38
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,38 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**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]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.

View File

@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**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.

41
.github/workflows/maven-publish.yml vendored Normal file
View File

@@ -0,0 +1,41 @@
name: Publish Forge
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 11
uses: actions/setup-java@v3
with:
java-version: '11'
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/Publish to GitHub Packages Apache Maven
run: |
export DISPLAY=":1"
Xvfb :1 -screen 0 800x600x8 &
mvn -U -B clean -P windows-linux install release:clean release:prepare release:perform -T 1C -Dcardforge-repo.username=${{ secrets.FTP_USERNAME }} -Dcardforge-repo.password=${{ secrets.FTP_PASSWORD }}
env:
GITHUB_TOKEN: ${{ github.token }}

34
.github/workflows/stale.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
# 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

29
.github/workflows/test-build.yaml vendored Normal file
View File

@@ -0,0 +1,29 @@
name: Test build
on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
java: [ '8', '11' ]
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 -P windows-linux test

View File

@@ -0,0 +1,48 @@
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 11
uses: actions/setup-java@v3
with:
java-version: '11'
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"

86
.gitignore vendored Normal file
View File

@@ -0,0 +1,86 @@
# Ignore IDEA config files
*.idea
*.iml
*.tmp
.metadata
.recommenders
# Ignore Eclipse config files
.settings
.classpath
.project
# Ignore VS Code config files
.vscode/settings.json
.vscode/launch.json
.factorypath
# Ignore NetBeans config files
nbactions.xml
# Ignore binaries, temp files and test output, everywhere
target
test-output
bin
gen
*.log
# Ignore macOS Spotlight rubbish
.DS_Store
# ignore vim swapfiles
*.swp
# TODO: specify what these ignores are for (releasing?)
forge.profile.properties
/jgv.txt
pom.xml.next
pom.xml.releaseBackup
pom.xml.tag
release.properties
# Ignore mobile-related resources
forge-gui-android/res/*/*
!forge-gui-android/res/*/ic_launcher.png
!forge-gui-android/res/*/ic_launcher*.png
!forge-gui-android/res/layout/main.xml
forge-gui-android/*.keystore
forge-gui-android/**/Thumbs.db
forge-gui-mobile-dev/**/Thumbs.db
forge-gui-mobile-dev/res
forge-gui-mobile-dev/testAssets
forge-gui/res/cardsfolder/*.bat
forge-gui/res/PerSetTrackingResults
forge-gui/res/decks
forge-gui/res/layouts
forge-gui/res/pics*
forge-gui/res/pics_product
forge-gui/res/skins/**/PerSetTrackingResults
forge-gui/res/skins/**/decks
forge-gui/res/skins/**/layouts
forge-gui/res/skins/**/pics*
forge-gui/res/skins/**/pics_product
forge-gui/res/quest/world/1996-05[!!-~]Ice[!!-~]Age/duels/.directory
forge-gui/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

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

23
.mvn/local-settings.xml Normal file
View File

@@ -0,0 +1,23 @@
<!--
Derived from: https://stackoverflow.com/a/67002852
-->
<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">
<mirrors>
<mirror>
<id>4thline-repo-http-unblocker</id>
<mirrorOf>4thline-repo</mirrorOf>
<name></name>
<url>http://4thline.org/m2</url>
</mirror>
</mirrors>
<servers>
<server>
<id>cardforge-repo</id>
<username>${cardforge-repo.username}</username>
<password>${cardforge-repo.password}</password>
</server>
</servers>
</settings>

2
.mvn/maven.config Normal file
View File

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

BIN
AppIcon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

674
LICENSE Normal file
View File

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

228
README.md Normal file
View File

@@ -0,0 +1,228 @@
# Forge
[Official repo](https://github.com/Card-Forge/forge.git).
Dev instructions here: [Getting Started](https://github.com/Card-Forge/forge/wiki) (Somewhat outdated)
Discord channel [here](https://discord.gg/fWfNgCUNRq)
## Requirements / Tools
- you favourite Java IDE (IntelliJ, Eclipse, VSCodium, Emacs, Vi...)
- Java JDK 8 or later (some IDEs such as Eclipse require JDK11+, whereas the Android build currently only works with JDK8)
- 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`
## Eclipse
Eclipse includes Maven integration so a separate install is not necessary. For other IDEs, your mileage may vary.
### 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 8 or newer required. If you execute `java -version` at the shell or command prompt, it should report version 1.8 or later.
- Install Eclipse 2018-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. That said, it is still possible to build and debug Android platforms.
#### Android SDK
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 8.0.0 (API 26) SDK Platform
- Google USB Driver (in case your phone is not detected by ADB)
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 or later (last tested with 7.0.1) from https://github.com/Guardsquare/proguard
- Go to the Android SDK install path. Rename the tools/proguard/ path to tools/proguard-4.7/.
- Extract your Proguard version to the Android SDK install path under tools/. You will need to either rename the dir proguard-<your-version> to proguard/ or, if your filesystem supports it, use a symbolic link (the later is highly recommended), such as `ln -s proguard proguard-<your-version>`.
#### 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://github.com/Card-Forge/forge/wiki/IntelliJ-setup).
## 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
#### 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.

21
checkstyle.xml Normal file
View File

@@ -0,0 +1,21 @@
<?xml version="1.0"?>
<!DOCTYPE module PUBLIC
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
"http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
<!--
Checkstyle is very configurable.
http://checkstyle.sf.net (or in your downloaded distribution).
-->
<module name="Checker">
<module name="TreeWalker">
<module name="RedundantImport"/>
<module name="UnusedImports">
<!-- <property name="processJavadoc" value="false"/> -->
</module>
</module>
</module>

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 208 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 169 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

299
forge-adventure/pom.xml Normal file
View File

@@ -0,0 +1,299 @@
<?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>1.6.57-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>forge-adventure</artifactId>
<packaging>jar</packaging>
<name>Forge Adventure</name>
<repositories>
<repository>
<id>gdx-nightlies</id>
<url>https://oss.sonatype.org/content/repositories/snapshots/</url>
</repository>
<repository>
<id>jitpack.io</id>
<url>https://jitpack.io</url>
</repository>
</repositories>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<resources>
<resource>
<directory>${project.basedir}</directory>
<includes>
<include>**/*.vert</include>
<include>**/*.frag</include>
<include>**/title_bg_lq.png</include>
<include>**/transition.png</include>
<include>**/adv_bg_texture.jpg</include>
<include>**/adv_bg_splash.png</include>
<include>**/bg_splash.png</include>
<include>**/bg_texture.jpg</include>
<include>**/font1.ttf</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>com.akathist.maven.plugins.launch4j</groupId>
<artifactId>launch4j-maven-plugin</artifactId>
<version>1.7.25</version>
<executions>
<execution>
<id>l4j-adv</id>
<phase>package</phase>
<goals>
<goal>launch4j</goal>
</goals>
<configuration>
<headerType>gui</headerType>
<outfile>${project.build.directory}/forge-adventure-editor-java8.exe</outfile>
<jar>${project.build.finalName}-jar-with-dependencies.jar</jar>
<dontWrapJar>true</dontWrapJar>
<errTitle>forge</errTitle>
<icon>src/main/config/forge-adventure-editor.ico</icon>
<classPath>
<mainClass>forge.adventure.Main</mainClass>
<addDependencies>false</addDependencies>
<preCp>anything</preCp>
</classPath>
<jre>
<minVersion>1.8.0</minVersion>
<maxHeapSize>4096</maxHeapSize>
<opts>
<opt>-Dfile.encoding=UTF-8</opt>
</opts>
</jre>
<versionInfo>
<fileVersion>
1.0.0.0
</fileVersion>
<txtFileVersion>
1.0.0.0
</txtFileVersion>
<fileDescription>Forge</fileDescription>
<copyright>Forge</copyright>
<productVersion>
1.0.0.0
</productVersion>
<txtProductVersion>
1.0.0.0
</txtProductVersion>
<productName>forge-adventure-editor</productName>
<internalName>forge-adventure-editor</internalName>
<originalFilename>forge-adventure-editor-java8.exe</originalFilename>
</versionInfo>
</configuration>
</execution>
<!--extra-->
<execution>
<id>l4j-adv2</id>
<phase>package</phase>
<goals>
<goal>launch4j</goal>
</goals>
<configuration>
<headerType>gui</headerType>
<outfile>${project.build.directory}/forge-adventure-editor.exe</outfile>
<jar>${project.build.finalName}-jar-with-dependencies.jar</jar>
<dontWrapJar>true</dontWrapJar>
<errTitle>forge</errTitle>
<downloadUrl>https://www.oracle.com/java/technologies/downloads/</downloadUrl>
<icon>src/main/config/forge-adventure-editor.ico</icon>
<classPath>
<mainClass>forge.adventure.Main</mainClass>
<addDependencies>false</addDependencies>
<preCp>anything</preCp>
</classPath>
<jre>
<minVersion>11.0.1</minVersion>
<jdkPreference>jdkOnly</jdkPreference>
<maxHeapSize>4096</maxHeapSize>
<opts>
<opt>-Dfile.encoding=UTF-8</opt>
<opt>--add-opens java.base/java.lang=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.math=ALL-UNNAMED</opt>
<opt>--add-opens java.base/jdk.internal.misc=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.nio=ALL-UNNAMED</opt>
<opt>--add-opens=java.base/sun.nio.ch=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.util=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.lang.reflect=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.text=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/java.awt=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/java.awt.font=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/java.awt.image=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/java.awt.color=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/sun.awt.image=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/javax.swing=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/javax.swing.border=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/javax.swing.event=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/sun.swing=ALL-UNNAMED</opt>
<opt>--add-opens java.desktop/java.beans=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.util.concurrent=ALL-UNNAMED</opt>
<opt>--add-opens java.base/java.net=ALL-UNNAMED</opt>
<opt>-Dio.netty.tryReflectionSetAccessible=true</opt>
</opts>
</jre>
<versionInfo>
<fileVersion>
1.0.0.0
</fileVersion>
<txtFileVersion>
1.0.0.0
</txtFileVersion>
<fileDescription>Forge</fileDescription>
<copyright>Forge</copyright>
<productVersion>
1.0.0.0
</productVersion>
<txtProductVersion>
1.0.0.0
</txtProductVersion>
<productName>forge-adventure-editor</productName>
<internalName>forge-adventure-editor</internalName>
<originalFilename>forge-adventure-editor.exe</originalFilename>
</versionInfo>
</configuration>
</execution>
<!--extra-->
</executions>
</plugin>
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<basedir>${basedir}/${configSourceDirectory}</basedir>
<filesToInclude>forge-adventure-editor.sh, forge-adventure-editor-mac.sh, forge-adventure-editor.command, forge-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>
</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>com.badlogicgames.gdx</groupId>
<artifactId>gdx</artifactId>
<version>1.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.badlogicgames.gdx</groupId>
<artifactId>gdx-platform</artifactId>
<version>1.11.0</version>
<classifier>natives-desktop</classifier>
</dependency>
<dependency>
<groupId>com.badlogicgames.gdx</groupId>
<artifactId>gdx-freetype</artifactId>
<version>1.11.0</version>
</dependency>
<dependency>
<groupId>com.badlogicgames.gdx</groupId>
<artifactId>gdx-backend-lwjgl</artifactId>
<version>1.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.badlogicgames.gdx</groupId>
<artifactId>gdx-tools</artifactId>
<version>1.11.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.badlogicgames.gdx</groupId>
<artifactId>gdx-freetype-platform</artifactId>
<version>1.11.0</version>
<classifier>natives-desktop</classifier>
</dependency>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-gui</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-gui-mobile</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.jetbrains</groupId>
<artifactId>annotations</artifactId>
<version>22.0.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.badlogicgames.gdx-controllers</groupId>
<artifactId>gdx-controllers-desktop</artifactId>
<version>2.2.3-SNAPSHOT</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
</project>

View File

@@ -0,0 +1,14 @@
# 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

View File

@@ -0,0 +1,16 @@
#ifdef GL_ES
precision mediump float;
#endif
varying vec4 v_color;
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform float u_grayness;
uniform float u_bias;
void main() {
vec4 c = v_color * texture2D(u_texture, v_texCoords);
float grey = dot( c.rgb, vec3(0.22, 0.707, 0.071) );
vec3 blendedColor = mix(c.rgb, vec3(grey), u_grayness);
gl_FragColor = mix(vec4(0.0, 0.0, 0.0, 1.0), vec4(blendedColor.rgb, c.a), u_bias);
}

View File

@@ -0,0 +1,14 @@
attribute vec4 a_position;
attribute vec4 a_color;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec4 v_color;
varying vec2 v_texCoords;
void main() {
v_color = a_color;
v_texCoords = a_texCoord0;
gl_Position = u_projTrans * a_position;
}

View File

@@ -0,0 +1,40 @@
#ifdef GL_ES
precision mediump float;
precision mediump int;
#endif
uniform sampler2D u_texture;
uniform vec2 u_viewportInverse;
uniform vec3 u_color;
uniform float u_offset;
uniform float u_step;
varying vec4 v_color;
varying vec2 v_texCoord;
#define ALPHA_VALUE_BORDER 0.5
void main() {
vec2 T = v_texCoord.xy;
float alpha = 0.0;
bool allin = true;
for( float ix = -u_offset; ix < u_offset; ix += u_step )
{
for( float iy = -u_offset; iy < u_offset; iy += u_step )
{
float newAlpha = texture2D(u_texture, T + vec2(ix, iy) * u_viewportInverse).a;
allin = allin && newAlpha > ALPHA_VALUE_BORDER;
if (newAlpha > ALPHA_VALUE_BORDER && newAlpha >= alpha)
{
alpha = newAlpha;
}
}
}
if (allin)
{
alpha = 0.0;
}
gl_FragColor = vec4(u_color,alpha);
}

View File

@@ -0,0 +1,16 @@
uniform mat4 u_projTrans;
attribute vec4 a_position;
attribute vec2 a_texCoord0;
attribute vec4 a_color;
varying vec4 v_color;
varying vec2 v_texCoord;
uniform vec2 u_viewportInverse;
void main() {
gl_Position = u_projTrans * a_position;
v_texCoord = a_texCoord0;
v_color = a_color;
}

View File

@@ -0,0 +1,26 @@
#ifdef GL_ES
#define PRECISION mediump
precision PRECISION float;
precision PRECISION int;
#else
#define PRECISION
#endif
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform float u_amount;
uniform float u_speed;
uniform float u_time;
uniform float u_bias;
void main () {
vec2 uv = v_texCoords;
uv.y += (cos((uv.y + (u_time * 0.04 * u_speed)) * 45.0) * 0.0019 * u_amount) + (cos((uv.y + (u_time * 0.1 * u_speed)) * 10.0) * 0.002 * u_amount);
uv.x += (sin((uv.y + (u_time * 0.07 * u_speed)) * 15.0) * 0.0029 * u_amount) + (sin((uv.y + (u_time * 0.1 * u_speed)) * 15.0) * 0.002 * u_amount);
vec4 texColor = texture2D(u_texture, uv);
gl_FragColor = mix(vec4(0.0, 0.0, 0.0, 1.0), texColor, u_bias);
}

View File

@@ -0,0 +1,57 @@
#ifdef GL_ES
precision mediump float;
#endif
varying vec2 v_texCoords;
uniform sampler2D u_texture;
uniform float u_time;
uniform float u_speed;
uniform float u_amount;
uniform vec2 u_viewport;
uniform vec2 u_position;
float random2d(vec2 n) {
return fract(sin(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);
}
float randomRange (in vec2 seed, in float min, in float max) {
return min + random2d(seed) * (max - min);
}
float insideRange(float v, float bottom, float top) {
return step(bottom, v) - step(top, v);
}
void main()
{
float time = floor(u_time * u_speed * 60.0);
vec3 outCol = texture2D(u_texture, v_texCoords).rgb;
float maxOffset = u_amount/2.0;
for (float i = 0.0; i < 2.0; i += 1.0) {
float sliceY = random2d(vec2(time, 2345.0 + float(i)));
float sliceH = random2d(vec2(time, 9035.0 + float(i))) * 0.25;
float hOffset = randomRange(vec2(time, 9625.0 + float(i)), -maxOffset, maxOffset);
vec2 uvOff = v_texCoords;
uvOff.x += hOffset;
if (insideRange(v_texCoords.y, sliceY, fract(sliceY+sliceH)) == 1.0){
outCol = texture2D(u_texture, uvOff).rgb;
}
}
float maxColOffset = u_amount / 6.0;
float rnd = random2d(vec2(time , 9545.0));
vec2 colOffset = vec2(randomRange(vec2(time , 9545.0), -maxColOffset, maxColOffset),
randomRange(vec2(time , 7205.0), -maxColOffset, maxColOffset));
if (rnd < 0.33) {
outCol.r = texture2D(u_texture, v_texCoords + colOffset).r;
} else if (rnd < 0.66) {
outCol.g = texture2D(u_texture, v_texCoords + colOffset).g;
} else {
outCol.b = texture2D(u_texture, v_texCoords + colOffset).b;
}
gl_FragColor = vec4(outCol, 1.0);
}

View File

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

View File

@@ -0,0 +1,25 @@
@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% GEQ 17 (
java --add-opens java.desktop/java.beans=ALL-UNNAMED --add-opens java.desktop/javax.swing.border=ALL-UNNAMED --add-opens java.desktop/javax.swing.event=ALL-UNNAMED --add-opens java.desktop/sun.swing=ALL-UNNAMED --add-opens java.desktop/java.awt.image=ALL-UNNAMED --add-opens java.desktop/java.awt.color=ALL-UNNAMED --add-opens java.desktop/sun.awt.image=ALL-UNNAMED --add-opens java.desktop/javax.swing=ALL-UNNAMED --add-opens java.desktop/java.awt=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED --add-opens java.base/jdk.internal.misc=ALL-UNNAMED --add-opens java.base/sun.nio.ch=ALL-UNNAMED --add-opens java.base/java.nio=ALL-UNNAMED --add-opens java.base/java.math=ALL-UNNAMED --add-opens java.base/java.util.concurrent=ALL-UNNAMED --add-opens java.base/java.net=ALL-UNNAMED -Dio.netty.tryReflectionSetAccessible=true -Xmx4096m -Dfile.encoding=UTF-8 -jar $project.build.finalName$
popd
exit /b 0
)
if %jver% GEQ 11 (
java --illegal-access=permit -Xmx4096m -Dfile.encoding=UTF-8 -jar $project.build.finalName$
popd
exit /b 0
)
java -Xmx4096m -Dfile.encoding=UTF-8 -jar $project.build.finalName$
popd

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

View File

@@ -0,0 +1,22 @@
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("", "", 0, 0);
Config.instance();
new EditorMainWindow();
}
}

View File

@@ -0,0 +1,156 @@
package forge.adventure.editor;
import forge.adventure.data.DialogData;
import javax.swing.*;
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 mapFlagName = new JTextField();
JTextField questFlagName = new JTextField();
JTextField advanceMapFlag = new JTextField();
JTextField advanceQuestFlag = new JTextField();
JTextField battleWithActorID = 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 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("Advance Map Flag name:",advanceMapFlag);
add("Advance Quest Flag name:",advanceQuestFlag);
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));
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 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(); //This is currently a boolean effect, eventually needs arguments
currentData.advanceMapFlag= advanceMapFlag.getText();
currentData.advanceQuestFlag= advanceQuestFlag.getText();
currentData.battleWithActorID= Integer.parseInt(battleWithActorID.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);
battleWithActorID.setText("" + currentData.battleWithActorID);
deleteMapObject.setText("" + 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

@@ -0,0 +1,141 @@
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 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(builder.toString());
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(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent 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

@@ -0,0 +1,125 @@
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

@@ -0,0 +1,171 @@
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))
return label;
BiomeStructureData.BiomeStructureDataMapping data=(BiomeStructureData.BiomeStructureDataMapping) value;
// Get the renderer component from parent class
label.setText(data.name);
if(editor.data!=null)
{
SwingAtlas itemAtlas=new SwingAtlas(Config.instance().getFile(editor.data.structureAtlasPath));
if(itemAtlas.has(data.name))
label.setIcon(itemAtlas.get(data.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

@@ -0,0 +1,136 @@
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

@@ -0,0 +1,84 @@
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

@@ -0,0 +1,155 @@
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

@@ -0,0 +1,242 @@
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

@@ -0,0 +1,85 @@
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

@@ -0,0 +1,139 @@
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))
return label;
DialogData dialog=(DialogData) value;
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

@@ -0,0 +1,121 @@
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(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
emitChanged(e);
}
});
}
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

@@ -0,0 +1,32 @@
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

@@ -0,0 +1,52 @@
package forge.adventure.editor;
import com.badlogic.gdx.tools.particleeditor.ParticleEditor;
import javax.swing.*;
import java.awt.*;
/**
* 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()
{
UIManager.LookAndFeelInfo[] var1 = UIManager.getInstalledLookAndFeels();
int var2 = var1.length;
for(int var3 = 0; var3 < var2; ++var3) {
UIManager.LookAndFeelInfo info = var1[var3];
if ("Nimbus".equals(info.getName())) {
try {
UIManager.setLookAndFeel(info.getClassName());
} catch (Throwable var6) {
}
break;
}
}
BorderLayout layout=new BorderLayout();
JToolBar toolBar = new JToolBar("toolbar");
JButton newButton=new JButton("open ParticleEditor");
newButton.addActionListener(e -> EventQueue.invokeLater(() ->new ParticleEditor()));
toolBar.add(newButton);
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());
setVisible(true);
setSize(800,600);
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow( this );
}
}

View File

@@ -0,0 +1,113 @@
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()).intValue();
currentData.lifeModifier= ((Integer)lifeModifier.getValue()).intValue();
currentData.moveSpeed= ((Float)moveSpeed.getValue()).floatValue();
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

@@ -0,0 +1,331 @@
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 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("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());
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= ((Double) speed.getValue()).floatValue();
currentData.spawnRate=((Double) spawnRate.getValue()).floatValue();
currentData.difficulty=((Double) difficulty.getValue()).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());
}
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(new Float(currentData.speed).doubleValue());
spawnRate.setValue(new Float(currentData.spawnRate).doubleValue());
difficulty.setValue(new Float(currentData.difficulty).doubleValue());
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

@@ -0,0 +1,132 @@
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

@@ -0,0 +1,58 @@
package forge.adventure.editor;
import forge.adventure.util.Config;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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(new ActionListener() {
@Override
public void actionPerformed(ActionEvent 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

@@ -0,0 +1,19 @@
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()).floatValue();
}
}

View File

@@ -0,0 +1,63 @@
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

@@ -0,0 +1,20 @@
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()).intValue();
}
}

View File

@@ -0,0 +1,86 @@
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()).intValue();
}
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

@@ -0,0 +1,128 @@
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))
return label;
ItemData Item=(ItemData) value;
// 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

@@ -0,0 +1,274 @@
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

@@ -0,0 +1,134 @@
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

@@ -0,0 +1,236 @@
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

@@ -0,0 +1,374 @@
package forge.adventure.editor;
import forge.adventure.data.AdventureQuestData;
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 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(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

@@ -0,0 +1,104 @@
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))
return label;
AdventureQuestData quest=(AdventureQuestData) value;
// 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

@@ -0,0 +1,606 @@
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 JCheckBox anyPOI = new JCheckBox("Any Point of Interest matching");
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 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 JLabel arenaLabel = new JLabel("Enter the arena and prove your worth. (Note: Please be sure the PoIs selected have an arena)");
private final JLabel clearLabel = new JLabel("Clear all enemies from the target area.");
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 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 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 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 mapFlagLabel = new JLabel("Have a map flag set to a minimum value");
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);
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);
here.setVisible(false);
mixedEnemies.setVisible(false);
enemySelector.setVisible(false);
count1Description.setVisible(false);
count2Description.setVisible(false);
count3Description.setVisible(false);
count1Spinner.setVisible(false);
count2Spinner.setVisible(false);
count3Spinner.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);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Clear":
clearLabel.setVisible(true);
nyi.setVisible(true);
poiPane.setVisible(true);
count1Description.setText("Target candidate percentile");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Percent variance");
count2Description.setVisible(true);
count2Spinner.setVisible(true);
anyPOI.setVisible(true);
here.setVisible(true);
poiTokenLabel.setVisible(true);
break;
case "Defeat":
defeatLabel.setVisible(true);
mixedEnemies.setVisible(true);
count1Description.setText("Number to defeat");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count2Description.setText("Maximum losses");
count2Description.setVisible(true);
count2Spinner.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 "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 "Hunt":
huntLabel.setVisible(true);
enemySelector.setVisible(true);
count1Description.setText("Lifespan (seconds to complete hunt before despawn)");
count1Description.setVisible(true);
count1Spinner.setVisible(true);
count1Spinner.setVisible(true);
break;
case "Leave":
leaveLabel.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);
break;
case "MapFlag":
mapFlagLabel.setVisible(true);
poiPane.setVisible(true);
here.setVisible(true);
anyPOI.setVisible(true);
mapFlagGroup.setVisible(true);
flagValueGroup.setVisible(true);
break;
case "QuestFlag":
nyi.setVisible(true);
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);
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);
break;
}
}
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);
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(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(mixedEnemies);
center.add(enemySelector);
center.add(count1Description);
center.add(count1Spinner);
center.add(count2Description);
center.add(count2Spinner);
center.add(count3Description);
center.add(count3Spinner);
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);
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);
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.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());
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

@@ -0,0 +1,139 @@
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))
return label;
AdventureQuestStage stageData=(AdventureQuestStage) value;
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

@@ -0,0 +1,107 @@
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

@@ -0,0 +1,144 @@
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.asList(CardType.CoreType.values()).stream().map(CardType.CoreType::toString).toArray(String[]::new));
TextListEdit superTypes =new TextListEdit(Arrays.asList(CardType.Supertype.values()).stream().map(CardType.Supertype::toString).toArray(String[]::new));
TextListEdit manaCosts =new TextListEdit();
TextListEdit keyWords =new TextListEdit(Arrays.asList(Keyword.values()).stream().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(new 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

@@ -0,0 +1,140 @@
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

@@ -0,0 +1,222 @@
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(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent 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

@@ -0,0 +1,92 @@
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.*;
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 (IOException 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

@@ -0,0 +1,94 @@
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

@@ -0,0 +1,132 @@
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;
import java.awt.*;
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(builder.toString());
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(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent 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

@@ -0,0 +1,118 @@
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

@@ -0,0 +1,235 @@
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 javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
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))
return label;
BiomeData biome=(BiomeData) value;
// 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(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent 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);
}
}
}
}

33
forge-ai/pom.xml Normal file
View File

@@ -0,0 +1,33 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>forge</artifactId>
<groupId>forge</groupId>
<version>1.6.57-SNAPSHOT</version>
</parent>
<artifactId>forge-ai</artifactId>
<name>Forge AI</name>
<dependencies>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-core</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>forge</groupId>
<artifactId>forge-game</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-math3</artifactId>
<version>3.6.1</version>
</dependency>
</dependencies>
</project>

View File

@@ -0,0 +1,121 @@
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 fromCardList(List<CardRules> cards) {
int totalCMC = 0;
int totalCount = 0;
int numLands = 0;
int maxCost = 0;
int[] maxPips = new int[6];
int maxColoredCost = 0;
for (CardRules rules : cards) {
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) {
List<CardRules> rules_list = 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()) {
CardRules rules = poolEntry.getKey().getRules();
rules_list.add(rules);
}
break;
default:
break; //ignore other sections
}
}
return fromCardList(rules_list);
}
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<CardRules> rules_list = new ArrayList<>();
for (Card c : player.getAllCards()) {
if (c.getPaperCard() == null) {
continue;
}
rules_list.add(c.getRules());
}
return fromCardList(rules_list);
}
return fromDeck(deck);
}
}

View File

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

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,390 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2011 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.ai;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import forge.game.card.Card;
import forge.game.player.Player;
/**
* <p>
* AiCardMemory class.
* </p>
*
* A simple class that allows the AI to "memorize" different cards on the battlefield (and possibly in other zones
* too, for instance as revealed from the opponent's hand) and assign them to different memory sets in order to help
* make somewhat more "educated" decisions to attack with certain cards or play certain spell abilities. Each
* AiController has its own memory that is created when the AI player is spawned. The card memory is accessible
* via AiController.getCardMemory.
*
* @author Forge
*/
public class AiCardMemory {
/**
* Defines the memory set in which the card is remembered
* (which, in its turn, defines how the AI utilizes the information
* about remembered cards).
*/
public enum MemorySet {
MANDATORY_ATTACKERS, // These creatures must attack this turn
TRICK_ATTACKERS, // These creatures will attack to try to provoke the opponent to block them into a combat trick
HELD_MANA_SOURCES_FOR_MAIN2, // These mana sources will not be used before Main 2
HELD_MANA_SOURCES_FOR_DECLBLK, // These mana sources will not be used before Combat - Declare Blockers
HELD_MANA_SOURCES_FOR_ENEMY_DECLBLK, // These mana sources will not be used before the opponent's Combat - Declare Blockers
HELD_MANA_SOURCES_FOR_NEXT_SPELL, // These mana sources will not be used until the next time the AI chooses a spell to cast
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
}
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;
private final Set<Card> memPaysTapCost;
private final Set<Card> memPaysSacCost;
private final Set<Card> memRevealedCards;
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<>();
this.memPaysTapCost = new HashSet<>();
this.memPaysSacCost = new HashSet<>();
this.memRevealedCards = new HashSet<>();
}
private Set<Card> getMemorySet(MemorySet set) {
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 PAYS_TAP_COST:
return memPaysTapCost;
case PAYS_SAC_COST:
return memPaysSacCost;
case REVEALED_CARDS:
return memRevealedCards;
default:
return null;
}
}
/**
* Checks if the given card was remembered in the given memory set.
*
* @param c
* the card
* @param set the memory set that is to be checked
* @return true, if the card is remembered in the given memory set
*/
public boolean isRememberedCard(Card c, MemorySet set) {
if (c == null) {
return false;
}
Set<Card> memorySet = getMemorySet(set);
return memorySet != null && memorySet.contains(c);
}
/**
* Checks if at least one card of the given name was remembered in the given memory set.
*
* @param cardName
* the card name
* @param set the memory set that is to be checked
* @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) {
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;
}
/**
* Checks if at least one card of the given name was remembered in the given memory set such
* that its owner is the given player.
*
* @param cardName
* the card name
* @param set the memory set that is to be checked
* @param owner the owner of the card
* @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) {
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;
}
/**
* Remembers the given card in the given memory set.
* @param c
* the card
* @param set the memory set to remember the card in
* @return true, if the card is successfully stored in the given memory set
*/
public boolean rememberCard(Card c, MemorySet set) {
if (c == null)
return false;
Set<Card> memorySet = getMemorySet(set);
if (memorySet != null) {
memorySet.add(c);
}
return true;
}
/**
* Forgets the given card in the given memory set.
* @param c
* the card
* @param set the memory set to forget the card in
* @return true, if the card was previously remembered in the given memory set and was successfully forgotten
*/
public boolean forgetCard(Card c, MemorySet set) {
if (c == null) {
return false;
}
if (!isRememberedCard(c, set)) {
return false;
}
Set<Card> memorySet = getMemorySet(set);
if (memorySet != null) {
memorySet.remove(c);
}
return true;
}
/**
* Forgets a single card with the given name in the given memory set.
* @param cardName
* the card name
* @param set the memory set to forget the card in
* @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) {
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;
}
/**
* Forgets a single card with the given name owned by the given player in the given memory set.
* @param cardName
* the card name
* @param set the memory set to forget the card in
* @param owner the owner of the card
* @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) {
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;
}
/**
* Determines if the memory set is empty.
* @param set the memory set to inspect.
* @return true, if the given memory set contains no remembered cards.
*/
public boolean isMemorySetEmpty(MemorySet set) {
return set == null || getMemorySet(set).isEmpty();
}
/**
* Clears the given memory set.
*/
public void clearMemorySet(MemorySet set) {
if (set != null) {
getMemorySet(set).clear();
}
}
/**
* Clears all memory sets stored in this card memory for the given player.
*/
public void clearAllRemembered() {
for (MemorySet memSet : MemorySet.values()) {
clearMemorySet(memSet);
}
}
// 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;
}
((PlayerControllerAi)ai.getController()).getAi().getCardMemory().rememberCard(c, set);
}
public static void rememberCard(AiController aic, Card c, MemorySet set) {
aic.getCardMemory().rememberCard(c, set);
}
public static void forgetCard(Player ai, Card c, MemorySet set) {
if (!ai.getController().isAI()) {
return;
}
((PlayerControllerAi)ai.getController()).getAi().getCardMemory().forgetCard(c, set);
}
public static void forgetCard(AiController aic, Card c, MemorySet set) {
aic.getCardMemory().forgetCard(c, set);
}
public static boolean isRememberedCard(Player ai, Card c, MemorySet set) {
if (!ai.getController().isAI()) {
return false;
}
return ((PlayerControllerAi)ai.getController()).getAi().getCardMemory().isRememberedCard(c, set);
}
public static boolean isRememberedCard(AiController aic, Card c, MemorySet set) {
return aic.getCardMemory().isRememberedCard(c, set);
}
public static boolean isRememberedCardByName(Player ai, String name, MemorySet set) {
if (!ai.getController().isAI()) {
return false;
}
return ((PlayerControllerAi)ai.getController()).getAi().getCardMemory().isRememberedCardByName(name, set);
}
public static boolean isRememberedCardByName(AiController aic, String name, MemorySet set) {
return aic.getCardMemory().isRememberedCardByName(name, set);
}
public static void clearMemorySet(Player ai, MemorySet set) {
if (!ai.getController().isAI()) {
return;
}
((PlayerControllerAi)ai.getController()).getAi().getCardMemory().clearMemorySet(set);
}
public static void clearMemorySet(AiController aic, MemorySet set) {
if (!isMemorySetEmpty(aic, set)) {
aic.getCardMemory().clearMemorySet(set);
}
}
public static boolean isMemorySetEmpty(Player ai, MemorySet set) {
if (!ai.getController().isAI()) {
return false;
}
return ((PlayerControllerAi)ai.getController()).getAi().getCardMemory().isMemorySetEmpty(set);
}
public static boolean isMemorySetEmpty(AiController aic, MemorySet set) {
return aic.getCardMemory().isMemorySetEmpty(set);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,811 @@
package forge.ai;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Lists;
import forge.card.CardType;
import forge.card.MagicColor;
import forge.game.Game;
import forge.game.GameEntityCounterTable;
import forge.game.card.*;
import forge.game.cost.*;
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.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 CardCollection discarded;
private final CardCollection tapped;
public AiCostDecision(Player ai0, SpellAbility sa, final boolean effect) {
super(ai0, effect, sa, sa.getHostCard());
discarded = new CardCollection();
tapped = new CardCollection();
}
@Override
public PaymentDecision visit(CostAddMana cost) {
int c = cost.getAbilityAmount(ability);
return PaymentDecision.number(c);
}
@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(),
Lists.newArrayList());
return PaymentDecision.type(choice);
}
@Override
public PaymentDecision visit(CostDiscard cost) {
final String type = cost.getType();
CardCollectionView hand = player.getCardsIn(ZoneType.Hand);
if (type.equals("LastDrawn")) {
if (!hand.contains(player.getLastDrawnCard())) {
return null;
}
return PaymentDecision.card(player.getLastDrawnCard());
} else if (cost.payCostFromSource()) {
if (!hand.contains(source)) {
return null;
}
return PaymentDecision.card(source);
} else if (type.equals("Hand")) {
if (hand.size() > 1 && ability.getActivatingPlayer() != null) {
hand = ability.getActivatingPlayer().getController().orderMoveToZoneList(hand, ZoneType.Graveyard, ability);
}
return PaymentDecision.card(hand);
}
if (type.contains("WithSameName")) {
return null;
}
int c = cost.getAbilityAmount(ability);
if (type.equals("Random")) {
CardCollectionView randomSubset = CardLists.getRandomSubList(new CardCollection(hand), c);
if (randomSubset.size() > 1 && ability.getActivatingPlayer() != null) {
randomSubset = ability.getActivatingPlayer().getController().orderMoveToZoneList(randomSubset, ZoneType.Graveyard, ability);
}
return PaymentDecision.card(randomSubset);
} 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, 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, Predicates.not(CardPredicates.sharesNameWith(chosen)));
c--;
}
return PaymentDecision.card(differentNames);
} else {
final AiController aic = ((PlayerControllerAi)player.getController()).getAi();
CardCollection result = aic.getCardsToDiscard(c, type.split(";"), ability, discarded);
if (result != null) {
discarded.addAll(result);
}
return PaymentDecision.card(result);
}
}
@Override
public PaymentDecision visit(CostDamage cost) {
int c = cost.getAbilityAmount(ability);
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostDraw cost) {
if (!cost.canPay(ability, player, isEffect())) {
return null;
}
int c = cost.getAbilityAmount(ability);
List<Player> res = cost.getPotentialPlayers(player, ability);
PaymentDecision decision = PaymentDecision.players(res);
decision.c = c;
return decision;
}
@Override
public PaymentDecision visit(CostExile cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
if (cost.getType().equals("All")) {
return PaymentDecision.card(player.getCardsIn(cost.getFrom()));
}
else if (cost.getType().contains("FromTopGrave")) {
return null;
}
int c = cost.getAbilityAmount(ability);
if (cost.getFrom().equals(ZoneType.Library)) {
return PaymentDecision.card(player.getCardsIn(ZoneType.Library, c));
}
else if (cost.zoneRestriction == 0) {
// TODO Determine exile from same zone for AI
return null;
} else {
CardCollectionView chosen = ComputerUtil.chooseExileFrom(player, cost, source, c, ability);
return null == chosen ? null : PaymentDecision.card(chosen);
}
}
@Override
public PaymentDecision visit(CostExileFromStack cost) {
List<SpellAbility> chosen = Lists.newArrayList();
for (SpellAbilityStackInstance si :source.getGame().getStack()) {
SpellAbility sp = si.getSpellAbility(true).getRootAbility();
if (si.getSourceCard().isValid(cost.getType().split(";"), source.getController(), source, sp)) {
chosen.add(sp);
}
}
return chosen.isEmpty() ? null : PaymentDecision.spellabilities(chosen);
}
@Override
public PaymentDecision visit(CostExiledMoveToGrave cost) {
CardCollection chosen = new CardCollection();
int c = cost.getAbilityAmount(ability);
CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Exile), cost.getType().split(";"), player, source, ability);
if (typeList.size() < c) {
return null;
}
CardLists.sortByPowerDesc(typeList);
for (int i = 0; i < c; i++) {
chosen.add(typeList.get(i));
}
return chosen.isEmpty() ? null : PaymentDecision.card(chosen);
}
@Override
public PaymentDecision visit(CostExert cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
int c = cost.getAbilityAmount(ability);
final CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, source, ability);
if (typeList.size() < c) {
return null;
}
CardLists.sortByPowerAsc(typeList);
final CardCollection res = new CardCollection();
for (int i = 0; i < c; i++) {
res.add(typeList.get(i));
}
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);
}
@Override
public PaymentDecision visit(CostRollDice cost) {
int c = cost.getAbilityAmount(ability);
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostGainControl cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
int c = cost.getAbilityAmount(ability);
CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, source, ability);
typeList = CardLists.filter(typeList, crd -> crd.canBeControlledBy(player));
if (typeList.size() < c) {
return null;
}
CardLists.sortByPowerAsc(typeList);
final CardCollection res = new CardCollection();
for (int i = 0; i < c; i++) {
res.add(typeList.get(i));
}
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)) {
if (opp.canGainLife()) {
oppsThatCanGainLife.add(opp);
}
}
if (oppsThatCanGainLife.isEmpty()) {
return null;
}
return PaymentDecision.players(oppsThatCanGainLife);
}
@Override
public PaymentDecision visit(CostMill cost) {
int c = cost.getAbilityAmount(ability);
CardCollectionView topLib = player.getCardsIn(ZoneType.Library, c);
return topLib.size() < c ? null : PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostPartMana cost) {
return PaymentDecision.number(0);
}
@Override
public PaymentDecision visit(CostPayLife cost) {
int c = cost.getAbilityAmount(ability);
if (!player.canPayLife(c, isEffect(), ability)) {
return null;
}
// activator.payLife(c, null);
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostPayEnergy cost) {
int c = cost.getAbilityAmount(ability);
if (!player.canPayEnergy(c)) {
return null;
}
return PaymentDecision.number(c);
}
@Override
public PaymentDecision visit(CostPutCardToLib cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
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());
}
int c = cost.getAbilityAmount(ability);
list = CardLists.getValidCards(list, cost.getType().split(";"), player, source, ability);
if (cost.isSameZone()) {
// Jotun Grunt
// TODO: improve AI
final FCollectionView<Player> players = game.getPlayers();
for (Player p : players) {
CardCollectionView enoughType = CardLists.filter(list, CardPredicates.isOwner(p));
if (enoughType.size() >= c) {
chosen.addAll(enoughType);
break;
}
}
chosen = chosen.subList(0, c);
} else {
chosen = ComputerUtil.choosePutToLibraryFrom(player, cost.getFrom(), cost.getType(), source, ability.getTargetCard(), c, ability);
}
return chosen.isEmpty() ? null : PaymentDecision.card(chosen);
}
@Override
public PaymentDecision visit(CostPutCounter cost) {
if (cost.payCostFromSource()) {
return PaymentDecision.card(source);
}
final CardCollection typeList = CardLists.getValidCards(player.getGame().getCardsIn(ZoneType.Battlefield),
cost.getType().split(";"), player, source, ability);
Card card;
if (cost.getType().equals("Creature.YouCtrl")) {
card = ComputerUtilCard.getWorstCreatureAI(typeList);
} else {
card = ComputerUtilCard.getWorstPermanentAI(typeList, false, false, false, false);
}
return PaymentDecision.card(card);
}
@Override
public PaymentDecision visit(CostTap cost) {
return PaymentDecision.number(0);
}
@Override
public PaymentDecision visit(CostTapType cost) {
String type = cost.getType();
boolean isVehicle = type.contains("+withTotalPowerGE");
CardCollection exclude = new CardCollection();
exclude.addAll(tapped);
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) {
totalP = type.split("withTotalPowerGE")[1];
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);
}
if (totap == null) {
//System.out.println("Couldn't find a valid card(s) to tap for: " + source.getName());
return null;
}
tapped.addAll(totap);
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());
}
if (cost.getAmount().equals("All")) {
// Does the AI want to use Sacrifice All?
return null;
}
int c = cost.getAbilityAmount(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);
}
@Override
public PaymentDecision visit(CostReturn cost) {
if (cost.payCostFromSource())
return PaymentDecision.card(source);
int c = cost.getAbilityAmount(ability);
CardCollectionView res = ComputerUtil.chooseReturnType(player, cost.getType(), source, ability.getTargetCard(), c, ability);
return res.isEmpty() ? null : PaymentDecision.card(res);
}
@Override
public PaymentDecision visit(CostReveal cost) {
final String type = cost.getType();
CardCollectionView hand = player.getCardsIn(cost.getRevealFrom());
if (cost.payCostFromSource()) {
if (!hand.contains(source)) {
return null;
}
return PaymentDecision.card(source);
}
if (cost.getType().equals("Hand")) {
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)) {
hand = CardLists.getValidCards(hand, type.split(";"), player, source, ability);
return PaymentDecision.card(getBestCreatureAI(hand));
}
int c = cost.getAbilityAmount(ability);
final AiController aic = ((PlayerControllerAi)player.getController()).getAi();
return PaymentDecision.card(aic.getCardsToDiscard(c, type.split(";"), ability));
}
@Override
public PaymentDecision visit(CostRevealChosenPlayer 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) {
Collections.sort(prefs, CardPredicates.compareByCounterType(cType));
for (Card prefCard : prefs) {
// already enough removed
if (stillToRemove <= removed) {
break;
}
int thisRemove = Math.min(prefCard.getCounters(cType), stillToRemove);
if (thisRemove > 0) {
removed += thisRemove;
table.put(null, prefCard, CounterType.get(cType), thisRemove);
}
}
}
return removed;
}
@Override
public PaymentDecision visit(CostRemoveAnyCounter cost) {
final int c = cost.getAbilityAmount(ability);
final Card originalHost = ObjectUtils.defaultIfNull(ability.getOriginalHost(), source);
if (c <= 0) {
return null;
}
CardCollectionView typeList = CardLists.getValidCards(player.getCardsIn(ZoneType.Battlefield), cost.getType().split(";"), player, source, ability);
// only cards with counters are of interest
typeList = CardLists.filter(typeList, CardPredicates.hasCounters());
// no target
if (typeList.isEmpty()) {
return null;
}
// TODO fill up a GameEntityCounterTable
// cost now has counter type or null
// the amount might be different from 1, could be X
// 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();
// currently the only one using remove any counter using a type uses p1p1
// the first things are benefit from removing counters
// try to remove -1/-1 counter from persist creature
if (c > toRemove && (cost.counter == null || cost.counter.is(CounterEnumType.M1M1))) {
List<Card> prefs = CardLists.filter(typeList, CardPredicates.hasCounter(CounterEnumType.M1M1), CardPredicates.hasKeyword(Keyword.PERSIST));
toRemove += removeCounter(table, prefs, CounterEnumType.M1M1, c - toRemove);
}
// try to remove +1/+1 counter from undying creature
if (c > toRemove && (cost.counter == null || cost.counter.is(CounterEnumType.P1P1))) {
List<Card> prefs = CardLists.filter(typeList, CardPredicates.hasCounter(CounterEnumType.P1P1), CardPredicates.hasKeyword(Keyword.UNDYING));
toRemove += removeCounter(table, prefs, CounterEnumType.P1P1, c - toRemove);
}
if (c > toRemove && cost.counter == null && originalHost.hasSVar("AIRemoveCounterCostPriority") && !"ANY".equalsIgnoreCase(originalHost.getSVar("AIRemoveCounterCostPriority"))) {
String[] counters = TextUtil.split(originalHost.getSVar("AIRemoveCounterCostPriority"), ',');
for (final String ctr : counters) {
CounterType ctype = CounterType.getType(ctr);
// ctype == null means any type
// any type is just used to return null for this
for (Card card : CardLists.filter(typeList, CardPredicates.hasCounter(ctype))) {
int thisRemove = Math.min(card.getCounters(ctype), c - toRemove);
if (thisRemove > 0) {
toRemove += thisRemove;
table.put(null, card, ctype, thisRemove);
}
}
}
}
// filter for negative counters
if (c > toRemove && cost.counter == null) {
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)) {
int over = Math.min(e.getValue(), c - toRemove);
if (over > 0) {
toRemove += over;
table.put(null, crd, e.getKey(), over);
}
}
}
}
}
}
// 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, 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()) {
for (final Card crd : useless) {
for (Map.Entry<CounterType, Integer> e : table.filterToRemove(crd).entrySet()) {
if (ComputerUtil.isUselessCounter(e.getKey(), crd)) {
int over = Math.min(e.getValue(), c - toRemove);
if (over > 0) {
toRemove += over;
table.put(null, crd, e.getKey(), over);
}
}
}
}
}
}
// try to remove Time counter from Chronozoa, it will generate more token
if (c > toRemove && (cost.counter == null || cost.counter.is(CounterEnumType.TIME))) {
List<Card> prefs = CardLists.filter(typeList, CardPredicates.hasCounter(CounterEnumType.TIME), CardPredicates.nameEquals("Chronozoa"));
toRemove += removeCounter(table, prefs, CounterEnumType.TIME, c - toRemove);
}
// 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, new Predicate<Card>() {
@Override
public boolean apply(final Card crd) {
// a Card without MaxQuestEffect doesn't need any Quest
// counters
int e = 0;
if (crd.hasSVar("MaxQuestEffect")) {
e = Integer.parseInt(crd.getSVar("MaxQuestEffect"));
}
return crd.getCounters(CounterEnumType.QUEST) > e;
}
});
Collections.sort(prefs, Collections.reverseOrder(CardPredicates.compareByCounterType(CounterEnumType.QUEST)));
for (final Card crd : prefs) {
int e = 0;
if (crd.hasSVar("MaxQuestEffect")) {
e = Integer.parseInt(crd.getSVar("MaxQuestEffect"));
}
int over = Math.min(crd.getCounters(CounterEnumType.QUEST) - e, c - toRemove);
if (over > 0) {
toRemove += over;
table.put(null, crd, CounterType.get(CounterEnumType.QUEST), over);
}
}
}
// remove Lore counters from Sagas to keep them longer
if (c > toRemove && (cost.counter == null || cost.counter.is(CounterEnumType.LORE))) {
List<Card> prefs = CardLists.filter(typeList, CardPredicates.hasCounter(CounterEnumType.LORE), CardPredicates.isType("Saga"));
// TODO add Svars and other stuff to keep the Sagas on specific levels
// also add a way for the AI to respond to the last Chapter ability to keep the Saga on the field if wanted
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
// without killing own non undying creatures in the process
// the amount of X should probably be tweaked for this
List<Card> withCtr = CardLists.filter(typeList, CardPredicates.hasCounter(cost.counter));
for (Card card : withCtr) {
int thisRemove = Math.min(card.getCounters(cost.counter), c - toRemove);
if (thisRemove > 0) {
toRemove += thisRemove;
table.put(null, card, cost.counter, thisRemove);
}
}
}
// Used to not return null
// Special part for CostPriority Any
if (c > toRemove && cost.counter == null && originalHost.hasSVar("AIRemoveCounterCostPriority") && "ANY".equalsIgnoreCase(originalHost.getSVar("AIRemoveCounterCostPriority"))) {
for (Card card : typeList) {
// TODO try not to remove to much positive counters from the same card
for (Map.Entry<CounterType, Integer> e : table.filterToRemove(card).entrySet()) {
int thisRemove = Math.min(e.getValue(), c - toRemove);
if (thisRemove > 0) {
toRemove += thisRemove;
table.put(null, card, e.getKey(), thisRemove);
}
}
}
}
// 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();
final String type = cost.getType();
int c;
final String sVar = ability.getSVar(amount);
if (amount.equals("All")) {
c = source.getCounters(cost.counter);
} else if (sVar.equals("Targeted$CardManaCost")) {
c = 0;
if (ability.getTargets().size() > 0) {
for (Card tgt : ability.getTargets().getTargetCards()) {
if (tgt.getManaCost() != null) {
c += tgt.getManaCost().getCMC();
}
}
}
} else {
c = cost.getAbilityAmount(ability);
}
if (!cost.payCostFromSource()) {
CardCollectionView typeList;
if (type.equals("OriginalHost")) {
typeList = new CardCollection(ability.getOriginalHost());
} else {
typeList = CardLists.getValidCards(player.getCardsIn(cost.zone), type.split(";"), player, source, ability);
}
for (Card card : typeList) {
if (card.getCounters(cost.counter) >= c) {
return PaymentDecision.card(card, c);
}
}
return null;
}
if (c > source.getCounters(cost.counter)) {
System.out.println("Not enough " + cost.counter + " on " + source.getName());
return null;
}
return PaymentDecision.card(source, c);
}
@Override
public PaymentDecision visit(CostUntapType cost) {
int c = cost.getAbilityAmount(ability);
CardCollectionView list = ComputerUtil.chooseUntapType(player, cost.getType(), source, cost.canUntapSource, c, ability);
if (list == null) {
System.out.println("Couldn't find a valid card to untap for: " + source.getName());
return null;
}
return PaymentDecision.card(list);
}
@Override
public PaymentDecision visit(CostUntap cost) {
return PaymentDecision.number(0);
}
@Override
public PaymentDecision visit(CostPayShards cost) {
return PaymentDecision.number(0);
}
@Override
public PaymentDecision visit(CostUnattach cost) {
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);
}
@Override
public boolean paysRightAfterDecision() {
return false;
}
}

View File

@@ -0,0 +1,21 @@
package forge.ai;
public enum AiPlayDecision {
WillPlay,
CantPlaySa,
CantPlayAi,
CantAfford,
CantAffordX,
WaitForMain2,
AnotherTime,
MissingNeededCards,
NeedsToPlayCriteriaNotMet,
TargetingFailed,
CostNotAcceptable,
WouldDestroyLegend,
WouldDestroyOtherPlaneswalker,
WouldBecomeZeroToughnessCreature,
WouldDestroyWorldEnchantment,
BadEtbEffects,
CurseEffects
}

View File

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

View File

@@ -0,0 +1,193 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2013 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.ai;
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.
* If a requested value is not loaded from a profile, default is returned.
*
* @author Forge
* @version $Id: AIProfile.java 20169 2013-03-08 08:24:17Z Agetian $
*/
public class AiProfileUtil {
private static Map<String, Map<AiProps, String>> loadedProfiles = new HashMap<>();
private static String AI_PROFILE_DIR;
private static final String AI_PROFILE_EXT = ".ai";
public static final String AI_PROFILE_RANDOM_MATCH = "Random (Every Match)";
public static final String AI_PROFILE_RANDOM_DUEL = "Random (Every Game)";
/** Builds an AI profile file name with full relative
* path based on the profile name.
* @param profileName the name of the profile.
* @return the full relative path and file name for the given profile.
*/
private static String buildFileName(final String profileName) {
return TextUtil.concatNoSpace(AI_PROFILE_DIR, "/", profileName, AI_PROFILE_EXT);
}
/**
* Load all profiles
*/
public static final void loadAllProfiles(String aiProfileDir) {
AI_PROFILE_DIR = aiProfileDir;
loadedProfiles.clear();
List<String> availableProfiles = getAvailableProfiles();
for (String profile : availableProfiles) {
loadedProfiles.put(profile, loadProfile(profile));
}
}
/**
* Load a single profile.
* @param profileName a profile to load.
*/
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;
}
final String[] split = line.split("=");
if (split.length == 2) {
profileMap.put(AiProps.valueOf(split[0]), split[1]);
} else if (split.length == 1 && line.endsWith("=")) {
profileMap.put(AiProps.valueOf(split[0]), "");
}
}
return profileMap;
}
/**
* Returns an AI property value for the current profile.
*
* @param fp0 an AI property.
* @return String
*/
public static String getAIProp(final LobbyPlayer p, final AiProps fp0) {
String val = null;
if (!(p instanceof LobbyPlayerAi))
return "";
String profile = ((LobbyPlayerAi) p).getAiProfile();
if (loadedProfiles.get(profile) != null) {
val = loadedProfiles.get(profile).get(fp0);
}
if (val == null) { val = fp0.getDefault(); }
return val;
}
/**
* Returns an array of strings containing all available profiles.
* @return ArrayList<String> - an array of strings containing all
* available profiles.
*/
public static List<String> getAvailableProfiles() {
final List<String> availableProfiles = new ArrayList<>();
final File dir = new File(AI_PROFILE_DIR);
final String[] children = dir.list();
if (children == null) {
System.err.println("AIProfile > can't find AI profile directory!");
} else {
for (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()));
}
}
}
return availableProfiles;
}
/**
* Returns an array of strings containing all available profiles including
* the special "Random" profiles.
* @return ArrayList<String> - an array list of strings containing all
* available profiles including special random profile tags.
*/
public static List<String> getProfilesDisplayList() {
final List<String> availableProfiles = new ArrayList<>();
availableProfiles.add(AI_PROFILE_RANDOM_MATCH);
availableProfiles.add(AI_PROFILE_RANDOM_DUEL);
availableProfiles.addAll(getAvailableProfiles());
return availableProfiles;
}
public static String[] getProfilesArray() {
return getProfilesDisplayList().toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
/**
* Returns a random personality from the currently available ones.
* @return String - a string containing a random profile from all the
* currently available ones.
*/
public static String getRandomProfile() {
return Aggregates.random(getAvailableProfiles());
}
/**
* Simple class test facility for AiProfileUtil.
*-/
public static void selfTest() {
final LobbyPlayer activePlayer = Singletons.getControl().getPlayer().getLobbyPlayer();
System.out.println(String.format("Current profile = %s", activePlayer.getAiProfile()));
ArrayList<String> profiles = getAvailableProfiles();
System.out.println(String.format("Available profiles: %s", profiles));
if (profiles.size() > 0) {
System.out.println(String.format("Loading all profiles..."));
loadAllProfiles();
System.out.println(String.format("Setting profile %s...", profiles.get(0)));
activePlayer.setAiProfile(profiles.get(0));
for (AiProps property : AiProps.values()) {
System.out.println(String.format("%s = %s", property, getAIProp(activePlayer, property)));
}
String randomProfile = getRandomProfile();
System.out.println(String.format("Loading random profile %s...", randomProfile));
activePlayer.setAiProfile(randomProfile);
for (AiProps property : AiProps.values()) {
System.out.println(String.format("%s = %s", property, getAIProp(activePlayer, property)));
}
}
}
*/
}

View File

@@ -0,0 +1,154 @@
/*
* Forge: Play Magic: the Gathering.
* Copyright (C) 2013 Forge Team
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package forge.ai;
/**
* AI personality profile settings identifiers, and their default values.
* When this class is instantiated, these enum values are used
* in a map that is populated with the current AI profile settings
* from the text file.
*/
public enum AiProps { /** */
DEFAULT_MAX_PLANAR_DIE_ROLLS_PER_TURN ("1"), /** */
DEFAULT_MIN_TURN_TO_ROLL_PLANAR_DIE ("3"), /** */
DEFAULT_PLANAR_DIE_ROLL_CHANCE ("50"), /** */
MULLIGAN_THRESHOLD ("5"), /** */
PLANAR_DIE_ROLL_HESITATION_CHANCE ("10"),
HOLD_LAND_DROP_FOR_MAIN2_IF_UNUSED ("0"), /** */
HOLD_LAND_DROP_ONLY_IF_HAVE_OTHER_PERMS ("true"), /** */
CHEAT_WITH_MANA_ON_SHUFFLE ("false"),
MOVE_EQUIPMENT_TO_BETTER_CREATURES ("from_useless_only"),
MOVE_EQUIPMENT_CREATURE_EVAL_THRESHOLD ("60"),
PRIORITIZE_MOVE_EQUIPMENT_IF_USELESS ("true"),
SAC_TO_REATTACH_TARGET_EVAL_THRESHOLD ("400"),
PREDICT_SPELLS_FOR_MAIN2 ("true"), /** */
RESERVE_MANA_FOR_MAIN2_CHANCE ("0"), /** */
PLAY_AGGRO ("false"),
CHANCE_TO_ATTACK_INTO_TRADE ("40"), /** */
RANDOMLY_ATKTRADE_ONLY_ON_LOWER_LIFE_PRESSURE ("true"), /** */
ATTACK_INTO_TRADE_WHEN_TAPPED_OUT ("false"), /** */
CHANCE_TO_ATKTRADE_WHEN_OPP_HAS_MANA ("0"), /** */
TRY_TO_AVOID_ATTACKING_INTO_CERTAIN_BLOCK ("true"), /** */
TRY_TO_HOLD_COMBAT_TRICKS_UNTIL_BLOCK ("false"), /** */
CHANCE_TO_HOLD_COMBAT_TRICKS_UNTIL_BLOCK ("30"), /** */
ENABLE_RANDOM_FAVORABLE_TRADES_ON_BLOCK ("true"), /** */
RANDOMLY_TRADE_EVEN_WHEN_HAVE_LESS_CREATS ("false"), /** */
MAX_DIFF_IN_CREATURE_COUNT_TO_TRADE ("1"), /** */
ALSO_TRADE_WHEN_HAVE_A_REPLACEMENT_CREAT ("true"), /** */
MAX_DIFF_IN_CREATURE_COUNT_TO_TRADE_WITH_REPL ("1"), /** */
MIN_CHANCE_TO_RANDOMLY_TRADE_ON_BLOCK ("30"), /** */
MAX_CHANCE_TO_RANDOMLY_TRADE_ON_BLOCK ("70"), /** */
CHANCE_DECREASE_TO_TRADE_VS_EMBALM ("30"), /** */
CHANCE_TO_TRADE_TO_SAVE_PLANESWALKER ("70"), /** */
CHANCE_TO_TRADE_DOWN_TO_SAVE_PLANESWALKER ("0"), /** */
THRESHOLD_TOKEN_CHUMP_TO_SAVE_PLANESWALKER ("135"), /** */
THRESHOLD_NONTOKEN_CHUMP_TO_SAVE_PLANESWALKER ("110"), /** */
CHUMP_TO_SAVE_PLANESWALKER_ONLY_ON_LETHAL ("true"), /** */
TRY_TO_PRESERVE_BUYBACK_SPELLS ("true"), /** */
MIN_SPELL_CMC_TO_COUNTER ("0"), /** */
CHANCE_TO_COUNTER_CMC_1 ("50"), /** */
CHANCE_TO_COUNTER_CMC_2 ("75"), /** */
CHANCE_TO_COUNTER_CMC_3 ("100"), /** */
ALWAYS_COUNTER_OTHER_COUNTERSPELLS ("true"), /** */
ALWAYS_COUNTER_DAMAGE_SPELLS ("true"), /** */
ALWAYS_COUNTER_CMC_0_MANA_MAKING_PERMS ("true"), /** */
ALWAYS_COUNTER_REMOVAL_SPELLS ("true"), /** */
ALWAYS_COUNTER_PUMP_SPELLS ("true"), /** */
ALWAYS_COUNTER_AURAS ("true"), /** */
ALWAYS_COUNTER_SPELLS_FROM_NAMED_CARDS (""), /** */
CHANCE_TO_COPY_OWN_SPELL_WHILE_ON_STACK ("30"), /** */
ALWAYS_COPY_SPELL_IF_CMC_DIFF ("2"), /** */
ACTIVELY_DESTROY_ARTS_AND_NONAURA_ENCHS ("true"), /** */
ACTIVELY_DESTROY_IMMEDIATELY_UNBLOCKABLE ("false"), /** */
ACTIVELY_PROTECT_VS_CURSE_AURAS("false"), /** */
DESTROY_IMMEDIATELY_UNBLOCKABLE_THRESHOLD ("2"), /** */
DESTROY_IMMEDIATELY_UNBLOCKABLE_ONLY_IN_DNGR ("true"), /** */
DESTROY_IMMEDIATELY_UNBLOCKABLE_LIFE_IN_DNGR ("5"), /** */
AVOID_TARGETING_CREATS_THAT_WILL_DIE ("true"), /** */
DONT_EVAL_KILLSPELLS_ON_STACK_WITH_PERMISSION ("true"), /** */
CHANCE_TO_CHAIN_TWO_DAMAGE_SPELLS("50"), /** */
HOLD_X_DAMAGE_SPELLS_FOR_MORE_DAMAGE_CHANCE("100"),
HOLD_X_DAMAGE_SPELLS_THRESHOLD("5"), /** */
PRIORITY_REDUCTION_FOR_STORM_SPELLS ("0"), /** */
USE_BERSERK_AGGRESSIVELY ("false"), /** */
MIN_COUNT_FOR_STORM_SPELLS ("0"), /** */
STRIPMINE_MIN_LANDS_IN_HAND_TO_ACTIVATE ("1"), /** */
STRIPMINE_MIN_LANDS_FOR_NO_TIMING_CHECK ("3"), /** */
STRIPMINE_MIN_LANDS_OTB_FOR_NO_TEMPO_CHECK ("6"), /** */
STRIPMINE_MAX_LANDS_TO_ATTEMPT_MANALOCKING ("3"), /** */
STRIPMINE_HIGH_PRIORITY_ON_SKIPPED_LANDDROP ("false"),
TOKEN_GENERATION_ABILITY_CHANCE ("80"), /** */
TOKEN_GENERATION_ALWAYS_IF_FROM_PLANESWALKER ("true"), /** */
TOKEN_GENERATION_ALWAYS_IF_OPP_ATTACKS ("true"), /** */
SCRY_NUM_LANDS_TO_STILL_NEED_MORE ("4"), /** */
SCRY_NUM_LANDS_TO_NOT_NEED_MORE ("7"), /** */
SCRY_NUM_CREATURES_TO_NOT_NEED_SUBPAR_ONES ("4"), /** */
SCRY_EVALTHR_CREATCOUNT_TO_SCRY_AWAY_LOWCMC ("3"), /** */
SCRY_EVALTHR_TO_SCRY_AWAY_LOWCMC_CREATURE ("160"), /** */
SCRY_EVALTHR_CMC_THRESHOLD ("3"), /** */
SCRY_IMMEDIATELY_UNCASTABLE_TO_BOTTOM ("false"), /** */
SCRY_IMMEDIATELY_UNCASTABLE_CMC_DIFF ("1"), /** */
SURVEIL_NUM_CARDS_IN_LIBRARY_TO_BAIL ("10"), /** */
SURVEIL_LIFEPERC_AFTER_PAYING_LIFE ("75"), /** */
COMBAT_ASSAULT_ATTACK_EVASION_PREDICTION ("true"), /** */
COMBAT_ATTRITION_ATTACK_EVASION_PREDICTION ("true"), /** */
CONSERVATIVE_ENERGY_PAYMENT_ONLY_IN_COMBAT ("true"), /** */
CONSERVATIVE_ENERGY_PAYMENT_ONLY_DEFENSIVELY ("true"), /** */
BOUNCE_ALL_TO_HAND_CREAT_EVAL_DIFF ("200"), /** */
BOUNCE_ALL_ELSEWHERE_CREAT_EVAL_DIFF ("200"), /** */
BOUNCE_ALL_TO_HAND_NONCREAT_EVAL_DIFF ("3"), /** */
BOUNCE_ALL_ELSEWHERE_NONCREAT_EVAL_DIFF ("3"), /** */
INTUITION_ALTERNATIVE_LOGIC ("false"), /** */
EXPLORE_MAX_CMC_DIFF_TO_PUT_IN_GRAVEYARD ("2"),
EXPLORE_NUM_LANDS_TO_STILL_NEED_MORE("2"), /** */
MOMIR_BASIC_LAND_STRATEGY("default"), /** */
MOJHOSTO_NUM_LANDS_TO_ACTIVATE_JHOIRA("5"), /** */
MOJHOSTO_CHANCE_TO_PREFER_JHOIRA_OVER_MOMIR ("50"), /** */
MOJHOSTO_CHANCE_TO_USE_JHOIRA_COPY_INSTANT ("20"), /** */
AI_IN_DANGER_THRESHOLD("4"), /** */
AI_IN_DANGER_MAX_THRESHOLD("4"), /** */
FLASH_ENABLE_ADVANCED_LOGIC("true"), /** */
FLASH_CHANCE_TO_OBEY_AMBUSHAI("100"), /** */
FLASH_CHANCE_TO_CAST_DUE_TO_ETB_EFFECTS("100"), /** */
FLASH_CHANCE_TO_CAST_FOR_ETB_BEFORE_MAIN1("10"), /** */
FLASH_CHANCE_TO_RESPOND_TO_STACK_WITH_ETB("0"), /** */
FLASH_CHANCE_TO_CAST_AS_VALUABLE_BLOCKER("100"),
FLASH_USE_BUFF_AURAS_AS_COMBAT_TRICKS("true"),
FLASH_BUFF_AURA_CHANCE_TO_CAST_EARLY("1"),
FLASH_BUFF_AURA_CHANCE_CAST_AT_EOT("5"),
FLASH_BUFF_AURA_CHANCE_TO_RESPOND_TO_STACK("100"),
BLINK_RELOAD_PLANESWALKER_CHANCE("30"), /** */
BLINK_RELOAD_PLANESWALKER_MAX_LOYALTY("2"), /** */
BLINK_RELOAD_PLANESWALKER_LOYALTY_DIFF("2"); /** */
// Experimental features, must be promoted or removed after extensive testing and, ideally, defaulting
// <-- There are no experimental options here -->
private final String strDefaultVal;
/** @param s0 &emsp; {@link java.lang.String} */
AiProps(final String s0) {
this.strDefaultVal = s0;
}
/** @return {@link java.lang.String} */
public String getDefault() {
return strDefaultVal;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,413 @@
package forge.ai;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.collect.Lists;
import forge.card.CardStateName;
import forge.game.Game;
import forge.game.GameActionUtil;
import forge.game.ability.ApiType;
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.Presets;
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.player.Player;
import forge.game.spellability.OptionalCostValue;
import forge.game.spellability.SpellAbility;
import forge.game.spellability.SpellAbilityStackInstance;
import forge.game.zone.ZoneType;
public class ComputerUtilAbility {
public static CardCollection getAvailableLandsToPlay(final Game game, final Player player) {
if (!game.getStack().isEmpty() || !game.getPhaseHandler().getPhase().isMain()) {
return null;
}
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, 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, c.getController(), c, null);
if (list.isEmpty()) {
return false;
}
}
return player.canPlayLand(c);
}
});
final CardCollection landsNotInHand = new CardCollection(player.getCardsIn(ZoneType.Graveyard));
landsNotInHand.addAll(game.getCardsIn(ZoneType.Exile));
if (!player.getCardsIn(ZoneType.Library).isEmpty()) {
landsNotInHand.add(player.getCardsIn(ZoneType.Library).get(0));
}
for (final Card crd : landsNotInHand) {
if (!(crd.isLand() || (crd.isFaceDown() && crd.getState(CardStateName.Original).getType().isLand()))) {
continue;
}
if (!crd.mayPlay(player).isEmpty()) {
landList.add(crd);
}
}
if (landList.isEmpty()) {
return null;
}
return landList;
}
public static CardCollection getAvailableCards(final Game game, final Player player) {
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));
}
all.addAll(game.getPlayers().getCardsIn(ZoneType.Exile));
all.addAll(game.getPlayers().getCardsIn(ZoneType.Battlefield));
return all;
}
public static List<SpellAbility> getSpellAbilities(final CardCollectionView l, final Player player) {
final List<SpellAbility> spellAbilities = Lists.newArrayList();
for (final Card c : l) {
spellAbilities.addAll(c.getAllPossibleAbilities(player, false));
}
return spellAbilities;
}
public static List<SpellAbility> getOriginalAndAltCostAbilities(final List<SpellAbility> originList, final Player player) {
final List<SpellAbility> newAbilities = Lists.newArrayList();
List<SpellAbility> originListWithAddCosts = Lists.newArrayList();
for (SpellAbility sa : originList) {
// If this spell has alternative additional costs, add them instead of the unmodified SA itself
sa.setActivatingPlayer(player, true);
originListWithAddCosts.addAll(GameActionUtil.getAdditionalCostSpell(sa));
}
for (SpellAbility sa : originListWithAddCosts) {
// determine which alternative costs are cheaper than the original and prioritize them
List<SpellAbility> saAltCosts = GameActionUtil.getAlternativeCosts(sa, player);
List<SpellAbility> priorityAltSa = Lists.newArrayList();
List<SpellAbility> otherAltSa = Lists.newArrayList();
for (SpellAbility altSa : saAltCosts) {
if (sa.getPayCosts().isOnlyManaCost()
&& altSa.getPayCosts().isOnlyManaCost() && sa.getPayCosts().getTotalMana().compareTo(altSa.getPayCosts().getTotalMana()) == 1) {
// the alternative cost is strictly cheaper, so why not? (e.g. Omniscience etc.)
priorityAltSa.add(altSa);
} else {
otherAltSa.add(altSa);
}
}
// add alternative costs as additional spell abilities
newAbilities.addAll(priorityAltSa);
newAbilities.add(sa);
newAbilities.addAll(otherAltSa);
}
final List<SpellAbility> result = Lists.newArrayList();
for (SpellAbility sa : newAbilities) {
sa.setActivatingPlayer(player, true);
// Optional cost selection through the AI controller
boolean choseOptCost = false;
List<OptionalCostValue> list = GameActionUtil.getOptionalCostValues(sa);
if (!list.isEmpty()) {
list = player.getController().chooseOptionalCosts(sa, list);
if (!list.isEmpty()) {
choseOptCost = true;
result.add(GameActionUtil.addOptionalCosts(sa, list));
}
}
// Add only one ability: either the one with preferred optional costs, or the original one if there are none
if (!choseOptCost) {
result.add(sa);
}
}
return result;
}
public static SpellAbility getTopSpellAbilityOnStack(Game game, SpellAbility sa) {
Iterator<SpellAbilityStackInstance> it = game.getStack().iterator();
if (!it.hasNext()) {
return null;
}
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(true);
}
return tgtSA;
}
public static SpellAbility getFirstCopySASpell(List<SpellAbility> spells) {
SpellAbility sa = null;
for (SpellAbility spell : spells) {
if (spell.getApi() == ApiType.CopySpellAbility) {
sa = spell;
break;
}
}
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);
return c != null ? c.getName() : "";
}
public static CardCollection getCardsTargetedWithApi(Player ai, CardCollection cardList, SpellAbility sa, ApiType api) {
// Returns a collection of cards which have already been targeted with the given API either in the parent ability,
// in the sub ability, or by something on stack. If "sa" is specified, the parent and sub abilities of this SA will
// be checked for targets. If "sa" is null, only the stack instances will be checked.
CardCollection targeted = new CardCollection();
if (sa != null) {
SpellAbility saSub = sa.getRootAbility();
while (saSub != null) {
if (saSub.getApi() == api && saSub.getTargets() != null) {
for (Card c : cardList) {
if (saSub.getTargets().getTargetCards().contains(c)) {
// Was already targeted with this API in a parent or sub SA
targeted.add(c);
}
}
}
saSub = saSub.getSubAbility();
}
}
for (SpellAbilityStackInstance si : ai.getGame().getStack()) {
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
if (si.getTargetChoices().getTargetCards().contains(c)) {
// Was already targeted by a spell ability instance on stack
targeted.add(c);
}
}
}
}
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() && a.getHostCard() != null && a.getHostCard().hasSVar("AIRollPlanarDieParams") && a.getHostCard().getSVar("AIRollPlanarDieParams").toLowerCase().matches(".*lowpriority\\$\\s*true.*")) {
return 1;
} else if (ApiType.RollPlanarDice == b.getApi() && b.getHostCard() != null && b.getHostCard().hasSVar("AIRollPlanarDieParams") && b.getHostCard().getSVar("AIRollPlanarDieParams").toLowerCase().matches(".*lowpriority\\$\\s*true.*")) {
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"));
}
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.getOracleText().contains("surge cost") && !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()) {
p += 4;
} else if (ApiType.Mana == sa.getApi()) {
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
Collections.sort(creatures, 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

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