Compare commits

...

28 commits

Author SHA1 Message Date
Daniel Stirba
eb148b6105 chore: Bump version to 1.2.4 in manifest.json and package.json 2025-01-12 16:29:14 +11:00
Daniel Stirba
a4e15ad385 style: Update OFCGDetails styles for light and dark themes 2025-01-12 16:28:08 +11:00
Daniel Stirba
8476645fb1 Forgot Package.json 2024-05-27 23:15:22 +10:00
Daniel Stirba
a0594d757e Updated Versioning 2024-05-27 23:15:18 +10:00
Daniel Stirba
3f5606ff2e Added a Command to "Open Fantasy Generator" 2024-05-27 22:50:15 +10:00
Daniel Stirba
9b6a1d580d Updated Versioning 2023-04-04 12:25:54 +10:00
Daniel Stirba
40068cc676 Added Weights to Loot, Added a Trading post Generator, Released to the community Hub 2023-04-04 12:24:00 +10:00
Daniel Stirba
a105b6f288 Conformed to Changed recommended 2023-02-24 19:57:22 +11:00
Daniel Stirba
c1e4a15c6a Forgot To Stage Packag.json 2023-02-19 21:21:14 +11:00
Daniel Stirba
c0e1ecb86d Updated Package.json to have Correct Versioning 2023-02-19 21:21:11 +11:00
Daniel Stirba
ca28a31938 Updated Versioning 2023-02-19 21:19:39 +11:00
Daniel Stirba
c9df27e40f Added Import/Export To Json Files. 2023-02-19 21:18:34 +11:00
Daniel Stirba
f0616bd167 Update Manifest.json 2023-02-18 14:14:18 +11:00
Daniel Stirba
6a54eb374f Cleaning up 2023-02-18 13:59:22 +11:00
Daniel Stirba
7ca735748d Complying with Plugin Review Guidelines 2023-02-18 13:55:35 +11:00
Daniel Stirba
81faf97f8a Updated Readme and Build Configuration 2023-02-18 13:14:05 +11:00
Daniel Stirba
5896b12edf Changed call out and Renamed and Reorganised folders 2023-02-18 12:54:30 +11:00
Daniel Stirba
7e48a2cfd2 Merge branch 'master' of https://github.com/Gregory-Jagermeister/Fantasy-Name-Generator 2023-02-18 12:32:16 +11:00
Daniel Stirba
4bd6221c97 Fixed Bug With Generators not getting right settings 2023-02-18 12:32:13 +11:00
Daniel Stirba
cee8f31a9c
Merge pull request #2 from Gregory-Jagermeister/add-license-1
Create LICENSE
2023-02-18 12:31:40 +11:00
Daniel Stirba
a1ec5639df
Create LICENSE 2023-02-18 12:30:09 +11:00
Daniel Stirba
8163d27e2d Cleaned up code so most things are more modular. 2023-02-18 12:20:36 +11:00
Daniel Stirba
aaa5ec9671 Completed the inline generation system 2023-02-18 10:45:22 +11:00
Daniel Stirba
39f3da4a03 Updated versioning 2023-02-10 12:21:33 +11:00
Daniel Stirba
cfd6f9bab5 Added Dungeon and Plot hook gens 2023-02-10 12:19:49 +11:00
Daniel Stirba
deaa5a16f5 Added The Abiltiy to Copy multiple results to the Clipboard 2023-02-09 23:05:51 +11:00
Daniel Stirba
8fcc4c1c18 Updated Manifest with correct version. 2023-02-09 01:10:33 +11:00
Daniel Stirba
84f28f01a0 Updated Readme. 2023-02-09 00:39:12 +11:00
26 changed files with 5397 additions and 1065 deletions

4
.gitignore vendored
View file

@ -20,3 +20,7 @@ data.json
# Exclude macOS Finder (System Explorer) View States
.DS_Store
fantasy-content-generator.zip
fantasy-content-generator
fantasy-content-generator/styles.css
builds

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>.

BIN
Obsidian_mrGSNRjLpe.gif Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 678 KiB

View file

@ -21,9 +21,40 @@ The Fantasy Content Generator Package (<https://www.npmjs.com/package/fantasy-co
![Example](Obsidian-Fantasy-Content-Generator-Compressed.gif)
## Custom Sources
In the settings of the plugin you will Find settings and options to add your own words and phrases to the generators, not all are added as of yet and there is no current plans to add more unless I get overwhelming requests for a particular one. The current Generators that can be customised are:
- loot generator
- Inn and Tavern generator
- Settlement Generator
- Drink Generator
- Group Generator.
- Currency.
- Dungeon Generator.
## Inline Generator
If you found yourself needing a quick name for an Elf or really wanting a quick dungeon description then look no further then the Inline generator. You can activate this by using the Callout token (Default is set to '@', can be changed in settings) and scrolling through the list of generators possible.
### Inline Example
![Example](Obsidian_mrGSNRjLpe.gif)
## Configuration
currently the only settings are the Currency settings, enable them in the settings and add your own currency determining how frequently they appear in loot generated and what currencies you would like to include.
Below is a table for all the settings in this plugin
| Setting | Options |
| ------- | ------- |
| Reset | Click the Reset Button to return to defaults |
| Call Out | Modify the call out used when using the inline Generator|
| Currency | Enable Currency use in generation, How often it occurs and add type of currency with rarity. |
| Settlements | Modify an Array of both Prefixed and Suffixes that can be used to generate settlements.|
| Inn & Taverns | Modify Arrays of Prefixes, Types, Nouns, Descriptions and Rumors that will generate for Inns and Taverns.|
| Drinks | Modify an array of both adjectives and nouns that will be used for the drinks generator |
| Loot | Modify an array of both adjectives and nouns that will be used for the loot generator |
| Group | adjust the Adjectives, Nouns, Plural Nouns, Group Types and Single Descriptors for the group generator|
| Dungeon | adjust the Adjectives, Nouns, Locations, Dungeon types and Random Descriptions used by the Dungeon Generator.|
## TO-DO
@ -33,6 +64,7 @@ currently the only settings are the Currency settings, enable them in the settin
- ~~Settlement Generator~~
- ~~Drink Generator~~
- ~~Group Generator.~~
- Randomization within a note.
- ~~Randomization within a note.~~
- Possibly more Generation type.
- Better UI
- ~~JSON Import And Export~~

436
editor/GeneratorModal.ts Normal file
View file

@ -0,0 +1,436 @@
import { App, DropdownComponent, Modal, Setting } from "obsidian";
import { nameByRace } from "fantasy-name-generator";
import { familyNameList } from "lists/humanFamilyNames";
import { generateShipName } from "generators/ship";
import { generatorReligions } from "generators/religions";
import { generatorAirships } from "generators/airship";
import { generatorDrinks } from "generators/drink";
import { generatorGroups } from "generators/groups";
import { generatorAnimal_groups } from "generators/animalGroups";
import { generatorMetals } from "generators/metal";
import { generatorMagical_trees } from "generators/magicalTrees";
import { elfFamilyNames } from "lists/elvenFamilyNames";
import { dwarfFamilyNames } from "lists/dwarvenFamilyNames";
import * as FCG from "fantasy-content-generator";
import { generateCityName } from "generators/city";
import { generateLoot } from "generators/loot";
import FantasyPlugin from "main";
import { generateInn } from "generators/inn";
import { generatePathfinderName } from "generators/Pathfinder/pathfinderName";
import { ISettlementDomainObject } from "fantasy-content-generator/dist/interfaces";
import { generateMiscellaneousArtifacts } from "generators/artifact";
import { generateDungeonName } from "generators/dungeon";
import { generatePlotHook } from "generators/plothook";
import { innGeneratorSettings, lootTables } from "settings/Datatypes";
const races: string[] = ["none", "none", "dungeon", "inn", "settlement", "none", "airships", "drinks", "artifacts", "loot", "metals", "magicaltrees", "ship", "none", "animalgroups", "groups", "religion", "none", "aasimars", "catfolk", "fetchlings", "halfelf", "halforc", "hobgoblin", "ifrits", "kobalds", "oreads", "ratfolk", "sylphs", "tengu", "tians", "tiefling", "undines", "angel", "cavePerson", "darkelf", "demon", "dragon", "drow", "dwarf", "elf", "fairy", "gnome", "goblin", "halfdemon", "halfling", "highelf", "highfairy", "human", "ogre", "orc", "none", "plothook"];
const racesDisplayName: string[] = ["Select a Generator to Start", "--[Settlements and Buildings]--", "Dungeons & Labryinths", "Inn's & Taverns", "Settlement", "--[Objects and Vehicles]--", "Airships", "Drinks", "Artifacts", "Loot And Treasure", "Metals", "Magical Trees", "Ship", "--[Groups and Religions]--", "Animal Groups", "Groups", "Religion", "--[Races]--", "Aasimars", "Catfolk", "Fetchlings", "Half-Elf", "Half-Orc", "Hobgoblin", "Ifrits", "Kobalds", "Oreads", "Ratfolk", "Sylphs", "Tengu", "Tians", "Tiefling", "Undines", "Angel", "Cave Person", "Dark Elf", "Demon", "Dragon", "Drow", "Dwarf", "Elf", "Fairy", "Gnome", "Goblin", "Half Demon", "Halfling", "High Elf", "High Fairy", "Human", "Ogre", "Orc", "--[Story Tools]--", "Plot & Story Hooks"];
const pathfinderFilter = ["aasimars", "catfolk", "fetchlings","halfelf","halforc","hobgoblin","ifrits","kobalds","oreads","ratfolk","sylphs","tengu","tians","tiefling","undines"];
let genSettings = {
race: "angel",
gender: "male",
multiNames: false
}
export class GeneratorModal extends Modal {
result: string | Error;
onSubmit: (result: string | Error) => void;
plugin: FantasyPlugin;
constructor(app: App, onSubmit: (result: string | Error) => void, plugin: FantasyPlugin) {
super(app);
this.onSubmit = onSubmit;
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
const amountToGen = 1;
contentEl.createEl("h1", { text: "Lets Generate!" });
contentEl.createEl("p", { text: "Welcome to the Fantasy Content Generator! Select the Generator for the name you would like to generate below and then fill out the form." });
contentEl.createEl("h2", { text: "Select the Generator." });
const select = new DropdownComponent(contentEl);
races.forEach((race,index) => {
select.addOption(race, racesDisplayName[index]);
})
const optionsDiv = contentEl.createDiv();
select.onChange((raceSelected) => {
switch (raceSelected) {
default:
this.generatorRaceSettings(optionsDiv, amountToGen, raceSelected);
break;
case "ship":
this.generatorCustomSettings(optionsDiv, amountToGen, generateShipName);
break;
case "dungeon":
this.generatorCustomSettings(optionsDiv, amountToGen, generateDungeonName, this.plugin.settings.dungeonSettings);
break;
case "plothook":
this.generatorCustomSettings(optionsDiv, amountToGen, generatePlotHook);
break;
case "religion":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorReligions);
break;
case "inn":
this.generatorInnSettings(optionsDiv, amountToGen, generateInn);
break;
case "airships":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorAirships);
break;
case "drinks":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorDrinks, this.plugin.settings.drinkSettings);
break;
case "groups":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorGroups, this.plugin.settings.groupSettings);
break;
case "animalgroups":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorAnimal_groups);
break;
case "metals":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorMetals);
break;
case "magicaltrees":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorMagical_trees);
break;
case "settlement":
this.generatorFCGSettlementSettings(optionsDiv, amountToGen, FCG.Settlements.generate);
break;
case "loot":
this.generatorLootSettings(optionsDiv, amountToGen, generateLoot, this.plugin.settings.enableCurrency, this.plugin.settings.currencyFrequency, this.plugin.settings.currencyTypes);
break;
case "artifacts":
this.generatorCustomSettings(optionsDiv, amountToGen, generateMiscellaneousArtifacts);
break;
case "none":
optionsDiv.innerHTML = "";
break;
}
});
}
generatorRaceSettings(settingsdiv: HTMLElement, genAmount: number, raceSelected: string) {
genSettings = {
race: "angel",
gender: "male",
multiNames: false
}
genSettings.race = raceSelected;
settingsdiv.empty();
settingsdiv.createEl("h3", { text: "Customise The Generation" });
new Setting(settingsdiv)
.setName("Male or Female?")
.addDropdown((drop) => {
drop.addOption("male", "Male");
drop.addOption("female", "Female");
drop.onChange((value) => {
genSettings.gender = value;
})
});
new Setting(settingsdiv)
.setName("Family Name?")
.addToggle((toggle) => {
toggle.onChange((value) => {
genSettings.multiNames = value;
})
})
let fullCopy = '';
new Setting(settingsdiv)
.setName("Amount")
.setDesc("How Many Records to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn.setButtonText("Generate")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
let firstName;
let familyName = '';
let fullName = '';
if (pathfinderFilter.includes(genSettings.race)) {
fullName = generatePathfinderName(genSettings.race, genSettings.gender, genSettings.multiNames);
} else {
type gender = 'male' | 'female' | undefined;
firstName = nameByRace(genSettings.race, { gender: genSettings.gender as gender });
if (genSettings.multiNames === true) {
familyName = genSettings.race.includes("human") || genSettings.race.includes("dwarf") || genSettings.race.includes("elf") ? " " + this.determineLastname(genSettings.race) : " " + nameByRace(genSettings.race, { gender: genSettings.gender as gender });
}
fullName = firstName + familyName;
}
new Setting(settingsdiv).addToggle((toggle) => {
toggle.onChange((value) => {
if (value === true) {
fullCopy += fullName + "\n";
} else {
const fullCIndex = fullCopy.indexOf(fullName);
fullCopy = fullCIndex === -1 ? fullCopy : fullCopy.slice(0, fullCIndex) + fullCopy.slice(fullCIndex + fullName.length);
}
})
.setValue(true);
}).setName(fullName);
}
}))
.addButton((btn) =>
btn
.setButtonText("Copy")
.setCta()
.onClick(() => {
if (fullCopy === '') {
this.result = new Error("Nothing Was Selected to Copy.");
} else {
this.result = fullCopy;
}
this.close();
this.onSubmit(this.result);
}));
}
generatorInnSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: (settings: innGeneratorSettings) => {name:string,description:string,rumors:string[]}) {
settingsdiv.empty();
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
let innList = '';
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
const innName = generatorFunction(this.plugin.settings.innSettings);
new Setting(settingsdiv).addToggle((toggle) => {
toggle.onChange((value) => {
const innString = innName.name + "\nDescription: " + innName.description + "\nRumors: " + innName.rumors;
if (value === true) {
innList += innString + "\n";
} else {
const fullCIndex = innList.indexOf(innString);
innList = fullCIndex === -1 ? innList : innList.slice(0, fullCIndex) + innList.slice(fullCIndex + innString.length);
}
})
.setValue(true);
}).setName(innName.name);
}
})).addButton((btn) =>
btn
.setButtonText("Copy")
.setCta()
.onClick(() => {
if (innList === '') {
this.result = new Error("Nothing Was Selected to Copy.");
} else {
this.result = innList;
}
this.close();
this.onSubmit(this.result);
}));
}
generatorLootSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: (enableCurrency:boolean, currencyFrequency: number, currencyTypes: object[], lootTable: lootTables) => string, enableCurrency:boolean, currencyFrequency: number, currencyTypes: object[]) {
settingsdiv.empty();
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
let list = '';
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
const shipName = generatorFunction(enableCurrency, currencyFrequency, currencyTypes, this.plugin.settings.lootSettings);
new Setting(settingsdiv).addToggle((toggle) => {
toggle.onChange((value) => {
if (value === true) {
list += shipName + "\n";
} else {
const fullCIndex = list.indexOf(shipName);
list = fullCIndex === -1 ? list : list.slice(0, fullCIndex) + list.slice(fullCIndex + shipName.length);
}
})
.setValue(true);
}).setName(shipName);
}
})).addButton((btn) =>
btn
.setButtonText("Copy")
.setCta()
.onClick(() => {
if (list === '') {
this.result = new Error("Nothing Was Selected to Copy.");
} else {
this.result = list;
}
this.close();
this.onSubmit(this.result);
}));
}
generatorFCGSettlementSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: () => ISettlementDomainObject) {
settingsdiv.empty();
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
let list = '';
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
const shipName = generatorFunction();
console.log(shipName);
const name = generateCityName(this.plugin.settings.citySettings);
const settlementString = "Name: " + name + "\nPopulation: " + shipName.population +"\nType: "+ this.formatString(shipName.type);
new Setting(settingsdiv).addToggle((toggle) => {
toggle.onChange((value) => {
if (value === true) {
list += settlementString + "\n\n";
} else {
const fullCIndex = list.indexOf(settlementString +"\n");
list = fullCIndex === -1 ? list : list.slice(0, fullCIndex) + list.slice(fullCIndex + settlementString.length);
}
})
.setValue(true);
}).setName(name);
}
})).addButton((btn) =>
btn
.setButtonText("Copy")
.setCta()
.onClick(() => {
if (list === '') {
this.result = new Error("Nothing Was Selected to Copy.");
} else {
this.result = this.formatStringList(list);
}
this.close();
this.onSubmit(this.result);
}));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
generatorCustomSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: (settings ?: any) => string, settings ?: any) {
settingsdiv.empty();
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
let list = "";
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
let shipName = '';
if (settings !== undefined) {
shipName = generatorFunction(settings);
} else {
shipName = generatorFunction();
}
new Setting(settingsdiv).addToggle((toggle) => {
toggle.onChange((value) => {
if (value === true) {
list += shipName + "\n\n";
} else {
const fullCIndex = list.indexOf(shipName);
list = fullCIndex === -1 ? list : list.slice(0, fullCIndex) + list.slice(fullCIndex + shipName.length);
}
})
.setValue(true);
}).setName(shipName);
}
})).addButton((btn) =>
btn
.setButtonText("Copy")
.setCta()
.onClick(() => {
if (list === '') {
this.result = new Error("Nothing Was Selected to Copy.");
} else {
this.result = this.formatStringList(list);
}
this.close();
this.onSubmit(this.result);
}));
}
determineLastname(race: string) {
if (race.includes("human")) {
return this.randomItemFromArray(familyNameList);
}
if (race.includes("elf")) {
return this.randomItemFromArray(elfFamilyNames);
}
if (race.includes("dwarf")) {
return this.randomItemFromArray(dwarfFamilyNames);
}
return "The Unknown"
}
randomItemFromArray(array:string[]) {
const randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
}
formatStringList(input: string) {
return input.split('\n').filter(s => s.trim() !== '').join('\n\n');
}
formatString(str:string) {
return str.split("_").map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
}
onClose() {
const { contentEl } = this;
genSettings = {
race: "angel",
gender: "male",
multiNames: false
}
contentEl.empty();
}
}

209
editor/InlineGenerator.ts Normal file
View file

@ -0,0 +1,209 @@
import { nameByRace } from "fantasy-name-generator";
import { generateCityName } from "generators/city";
import { generateDungeonName } from "generators/dungeon";
import { generateInn } from "generators/inn";
import { dwarfFamilyNames } from "lists/dwarvenFamilyNames";
import { elfFamilyNames } from "lists/elvenFamilyNames";
import { familyNameList } from "lists/humanFamilyNames";
import { titleLastNames } from "lists/titleLastNames";
import * as FCG from "fantasy-content-generator";
import FantasyPlugin from "main";
import { Editor, EditorPosition, EditorSuggest, EditorSuggestContext, EditorSuggestTriggerInfo } from "obsidian";
import { generatorAirships } from "generators/airship";
import { generatorDrinks } from "generators/drink";
import { generateMiscellaneousArtifacts } from "generators/artifact";
import { generateLoot } from "generators/loot";
import { generatorMetals } from "generators/metal";
import { generatorMagical_trees } from "generators/magicalTrees";
import { generateShipName } from "generators/ship";
import { generatorAnimal_groups } from "generators/animalGroups";
import { generatorGroups } from "generators/groups";
import { generatorReligions } from "generators/religions";
import { generatePathfinderName } from "generators/Pathfinder/pathfinderName";
import { generatePlotHook } from "generators/plothook";
import { generateTradingPost } from "generators/tradingPost";
type Generator = () => string | Error;
//An interface to be used with Getting the keys of the Generator object.
interface Generators {
[key: string]: Generator;
}
export class InlineGeneratorSuggester extends EditorSuggest<string> {
private getCompletions: () => string[]; // function to retrieve completions
startChar: EditorPosition
endChar: EditorPosition
plugin: FantasyPlugin
//An object storing all the Generator functions used by the particular selection
private generators: Generators = {
'TradingPost': () => "Trading Post Name: " + generateCityName(this.plugin.settings.citySettings) + "\n" + generateTradingPost(),
'ElfMale': () => nameByRace("elf", { gender: "male" }),
'ElfMaleLastname': () => nameByRace("elf", { gender: "male" }) + " " + elfFamilyNames[Math.floor(Math.random() * elfFamilyNames.length)],
'ElfFemale': () => nameByRace("elf", { gender: "female" }),
'ElfFemaleLastname': () => nameByRace("elf", { gender: "female" }) + " " + elfFamilyNames[Math.floor(Math.random() * elfFamilyNames.length)],
'Orc': () => nameByRace("orc"),
'OrcLastname': () => nameByRace("orc") + " " + titleLastNames[Math.floor(Math.random() * titleLastNames.length)],
'DwarfMale': () => nameByRace("elf", { gender: "male" }),
'DwarfMaleLastname': () => nameByRace("elf", { gender: "male" }) + " " + dwarfFamilyNames[Math.floor(Math.random() * dwarfFamilyNames.length)],
'DwarfFemale': () => nameByRace("elf", { gender: "female" }),
'DwarfFemaleLastname': () => nameByRace("elf", { gender: "female" }) + " " + dwarfFamilyNames[Math.floor(Math.random() * dwarfFamilyNames.length)],
'HumanMale': () => nameByRace("elf", { gender: "male" }),
'HumanFemale': () => nameByRace("elf", { gender: "female" }),
'HumanMaleLastname': () => nameByRace("elf", { gender: "male" }) + " " + familyNameList[Math.floor(Math.random() * familyNameList.length)],
'HumanFemaleLastname': () => nameByRace("elf", { gender: "female" }) + " " + familyNameList[Math.floor(Math.random() * familyNameList.length)],
"DungeonsLabryinths": () => generateDungeonName(this.plugin.settings.dungeonSettings),
"InnsTaverns": () => {
const innInfo = generateInn(this.plugin.settings.innSettings);
return innInfo.name + "\nDescription: " + innInfo.description + "\nRumors: " + innInfo.rumors;
},
"Settlement": () => {
const CityInfo = FCG.Settlements.generate();
const name = generateCityName(this.plugin.settings.citySettings);
return "Name: " + name + "\nPopulation: " + CityInfo.population + "\nType: " + CityInfo.type.split("_").map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()).join(" ");
},
"Airships": () => generatorAirships(),
"Drinks": () => generatorDrinks(this.plugin.settings.drinkSettings),
"Artifacts": () => generateMiscellaneousArtifacts(),
"LootTreasure": () => generateLoot(this.plugin.settings.enableCurrency, this.plugin.settings.currencyFrequency, this.plugin.settings.currencyTypes, this.plugin.settings.lootSettings),
"Metals": () => generatorMetals(),
"MagicalTrees": () => generatorMagical_trees(),
"Ship": () => generateShipName(),
"AnimalGroups": () => generatorAnimal_groups(),
"Groups": () => generatorGroups(this.plugin.settings.groupSettings),
"Religion": () => generatorReligions(),
"AasimarsLastname": () => generatePathfinderName("aasimars", "male", true),
"CatfolkLastname": () => generatePathfinderName("catfolk", "male", true),
"FetchlingsLastname": () => generatePathfinderName("fetchlings", "male", true),
"HalfElfLastname": () => generatePathfinderName("halfelf", "male", true),
"HalfOrcLastname": () => generatePathfinderName("halforc", "male", true),
"HobgoblinLastname": () => generatePathfinderName("hobgoblin", "male", true),
"IfritsLastname": () => generatePathfinderName("ifrits", "male", true),
"KobaldsLastname": () => generatePathfinderName("kobalds", "male", true),
"OreadsLastname": () => generatePathfinderName("oreads", "male", true),
"RatfolkLastname": () => generatePathfinderName("ratfolk", "male", true),
"SylphsLastname": () => generatePathfinderName("sylphs", "male", true),
"TenguLastname": () => generatePathfinderName("tengu", "male", true),
"TiansLastname": () => generatePathfinderName("tians", "male", true),
"TieflingLastname": () => generatePathfinderName("tiefling", "male", true),
"UndinesLastname": () => generatePathfinderName("undines", "male", true),
"AngelMaleLastname": () => nameByRace("angel", { gender: "male" }) + " " + nameByRace("angel", { gender: "male" }),
"AngelFemaleLastname": () => nameByRace("angel", { gender: "female" }) + " " + nameByRace("angel", { gender: "female" }),
"CavePersonMaleLastname": () => nameByRace("cavePerson", { gender: "male" }) + " " + nameByRace("cavePerson", { gender: "male" }),
"CavePersonFemaleLastname": () => nameByRace("cavePerson", { gender: "female" }) + " " + nameByRace("cavePerson", { gender: "female" }),
"DarkElfMaleLastname": () => nameByRace("darkelf", { gender: "male" }) + " " + nameByRace("darkelf", { gender: "male" }),
"DarkElfFemaleLastname": () => nameByRace("darkelf", { gender: "female" }) + " " + nameByRace("darkelf", { gender: "female" }),
"DemonLastname": () => nameByRace("demon") + " " + nameByRace("demon"),
"DragonMaleLastname": () => nameByRace("dragon", { gender: "male" }) + " " + nameByRace("dragon", { gender: "male" }),
"DragonFemaleLastname": () => nameByRace("dragon", { gender: "female" }) + " " + nameByRace("dragon", { gender: "female" }),
"DrowMaleLastname": () => nameByRace("drow", { gender: "male" }) + " " + nameByRace("drow", { gender: "male" }),
"DrowFemaleLastname": () => nameByRace("drow", { gender: "female" }) + " " + nameByRace("drow", { gender: "female" }),
"FairyMaleLastname": () => nameByRace("fairy", { gender: "male" }) + " " + nameByRace("fairy", { gender: "male" }),
"FairyFemaleLastname": () => nameByRace("fairy", { gender: "female" }) + " " + nameByRace("fairy", { gender: "female" }),
"GnomeMaleLastname": () => nameByRace("gnome", { gender: "male" }) + " " + nameByRace("gnome", { gender: "male" }),
"GnomeFemaleLastname": () => nameByRace("gnome", { gender: "female" }) + " " + nameByRace("gnome", { gender: "female" }),
"GoblinLastname": () => nameByRace("goblin") + " " + nameByRace("goblin"),
"HalfDemonMaleLastname": () => nameByRace("halfdemon", { gender: "male" }) + " " + nameByRace("halfdemon", { gender: "male" }),
"HalfDemonFemaleLastname": () => nameByRace("halfdemon", { gender: "female" }) + " " + nameByRace("halfdemon", { gender: "female" }),
"HalflingMaleLastname": () => nameByRace("halfling", { gender: "male" }) + " " + nameByRace("halfling", { gender: "male" }),
"HalflingFemaleLastname": () => nameByRace("halfling", { gender: "female" }) + " " + nameByRace("halfling", { gender: "female" }),
"HighElfMaleLastname": () => nameByRace("highelf", { gender: "male" }) + " " + nameByRace("highelf", { gender: "male" }),
"HighElfFemaleLastname": () => nameByRace("highelf", { gender: "female" }) + " " + nameByRace("highelf", { gender: "female" }),
"HighFairyMaleLastname": () => nameByRace("highfairy", { gender: "male" }) + " " + nameByRace("highfairy", { gender: "male" }),
"HighFairyFemaleLastname": () => nameByRace("highfairy", { gender: "female" }) + " " + nameByRace("angel", { gender: "female" }),
"OgreLastname": () => nameByRace("ogre") + " " + nameByRace("ogre"),
"Aasimars": () => generatePathfinderName("aasimars", "male", false),
"Catfolk": () => generatePathfinderName("catfolk", "male", false),
"Fetchlings": () => generatePathfinderName("fetchlings", "male", false),
"HalfElf": () => generatePathfinderName("halfelf", "male", false),
"HalfOrc": () => generatePathfinderName("halforc", "male", false),
"Hobgoblin": () => generatePathfinderName("hobgoblin", "male", false),
"Ifrits": () => generatePathfinderName("ifrits", "male", false),
"Kobalds": () => generatePathfinderName("kobalds", "male", false),
"Oreads": () => generatePathfinderName("oreads", "male", false),
"Ratfolk": () => generatePathfinderName("ratfolk", "male", false),
"Sylphs": () => generatePathfinderName("sylphs", "male", false),
"Tengu": () => generatePathfinderName("tengu", "male", false),
"Tians": () => generatePathfinderName("tians", "male", false),
"Tiefling": () => generatePathfinderName("tiefling", "male", false),
"Undines": () => generatePathfinderName("undines", "male", false),
"AngelMale": () => nameByRace("angel", { gender: "male" }),
"CavePersonMale": () => nameByRace("cavePerson", { gender: "male" }),
"DarkElfMale": () => nameByRace("darkelf", { gender: "male" }),
"DragonMale": () => nameByRace("dragon", { gender: "male" }),
"DrowMale": () => nameByRace("drow", { gender: "male" }),
"FairyMale": () => nameByRace("fairy", { gender: "male" }),
"GnomeMale": () => nameByRace("Gnome", { gender: "male" }),
"HalfDemonMale": () => nameByRace("halfdemon", { gender: "male" }),
"HalflingMale": () => nameByRace("halfling", { gender: "male" }),
"HighElfMale": () => nameByRace("highelf", { gender: "male" }),
"HighFairyMale": () => nameByRace("highfairy", { gender: "male" }),
"Ogre": () => nameByRace("ogre"),
"AngelFemale": () => nameByRace("angel", { gender: "female" }),
"CavePersonFemale": () => nameByRace("cavePerson", { gender: "female" }),
"DarkElfFemale": () => nameByRace("darkelf", { gender: "female" }),
"Demon": () => nameByRace("demon"),
"DragonFemale": () => nameByRace("dragon", { gender: "female" }),
"DrowFemale": () => nameByRace("drow", { gender: "female" }),
"FairyFemale": () => nameByRace("fairy", { gender: "female" }),
"GnomeFemale": () => nameByRace("gnome", { gender: "female" }),
"Goblin": () => nameByRace("goblin"),
"HalfDemonFemale": () => nameByRace("halfdemon", { gender: "female" }),
"HalflingFemale": () => nameByRace("halfling", { gender: "female" }),
"HighElfFemale": () => nameByRace("highelf", { gender: "female" }),
"HighFairyFemale": () => nameByRace("highfairy", { gender: "female" }),
"PlotStoryHooks": () => generatePlotHook(),
}
constructor(getCompletions: () => string[], plugin: FantasyPlugin) {
super(app);
this.getCompletions = getCompletions;
this.plugin = plugin;
}
onTrigger(
cursor: EditorPosition,
editor: Editor
): EditorSuggestTriggerInfo | null {
// check if the cursor is immediately following the Callout defined in settings
const callOut = this.plugin.settings.inlineCallout;
const escapedCallOut = callOut.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regEx = new RegExp(`${escapedCallOut}(\\S*)`);
const line = editor.getLine(cursor.line);
const match = line.slice(0, cursor.ch).match(regEx);
if (!match) {
return null;
}
const start = { line: cursor.line, ch: cursor.ch - match[1].length - callOut.length };
const end = { line: cursor.line, ch: cursor.ch };
this.startChar = start;
this.endChar = end;
return { start, end, query: match[1] };
}
getSuggestions(context: EditorSuggestContext): string[] {
return this.getCompletions().filter((s) => s.toLowerCase().startsWith(context.query.toLowerCase()));
}
renderSuggestion(value: string, el: HTMLElement): void {
el.createEl("div", { text: value });
}
selectSuggestion(value: string, _evt: MouseEvent | KeyboardEvent): void {
// execute the selected function if the function does not exist then return "not implemented"
let result: string | Error = "Not Implemented";
if (value in this.generators) {
result = this.generators[value]();
}
if (this.plugin.currentEditor) {
this.plugin.currentEditor.replaceRange(result.toString(), this.startChar, this.endChar);
}
}
}

View file

@ -31,7 +31,8 @@ const context = await esbuild.context({
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins],
...builtins,
],
format: "cjs",
target: "es2018",
logLevel: "info",

View file

@ -1,10 +1,35 @@
import { cityGeneratorSetting } from "main";
import { cityGeneratorSetting } from "settings/Datatypes";
export function generateCityName(settings : cityGeneratorSetting) {
const prefixes = settings.prefixArray;
const suffixes = settings.suffixArray;
const syllables = ["ab", "ac", "al", "am", "an", "ap", "apo", "ar", "arr", "as", "ast", "at", "ate", "au", "av", "ay", "aye", "ba", "be", "ben", "bo", "br", "bri", "bu", "bur", "ca", "cal", "car", "ce", "chi", "ci", "ck", "co", "com", "con", "cor", "cy", "d", "da", "dan", "dar", "de", "den", "di", "do", "dor", "du", "dur", "ed", "el", "en", "eon", "er", "es", "ey", "fa", "far", "fe", "fi", "fin", "fo", "for", "foy", "fr", "fu", "ga", "gal", "ge", "gi", "gil", "gin", "go", "gor", "gr", "gu", "ha", "han", "har", "he", "hi", "hin", "ho", "hoe", "hos", "hu", "ic", "il", "ill", "in", "ing", "ion", "ir", "irk", "is", "ja", "je", "jen", "jo", "ju", "ka", "ke", "ker", "ki", "kir", "ko", "la", "lan", "las", "le", "ler", "li", "lin", "lis", "lo", "lor", "loy", "lu", "ma", "mac", "mal", "man", "mas", "me", "mi", "mo", "mon", "mu", "mul", "mur", "na", "nal", "ne", "ni", "no", "nor", "nov", "nu", "och", "ode", "oka", "ol", "ome", "on", "op", "or", "ore", "os", "ou", "ous", "pa", "par", "pe", "pen", "pi", "po", "pol", "pon", "por", "pu", "qu", "ra", "re", "ri", "ro", "ru", "sa", "se", "si", "so", "su", "ta", "te", "ti", "to", "tu", "ul", "un", "ur", "us", "va", "ve", "vi", "vo", "vu", "wa", "we", "wi", "wo", "wu", "y", "ya", "ye", "yi", "yo", "yu", "za", "ze", "zi", "zo"];
const syllables = [
'ab', 'ac', 'ad', 'al', 'an', 'ap', 'ar', 'as', 'at', 'au',
'ba', 'be', 'bi', 'bo', 'bu',
'ca', 'ce', 'ci', 'co', 'cu',
'da', 'de', 'di', 'do', 'du',
'ea', 'eb', 'ec', 'ed', 'el', 'em', 'en', 'er', 'es', 'et', 'eu',
'fa', 'fe', 'fi', 'fo', 'fu',
'ga', 'ge', 'gi', 'go', 'gu',
'ha', 'he', 'hi', 'ho', 'hu',
'ia', 'ib', 'ic', 'id', 'ie', 'if', 'ig', 'il', 'im', 'in', 'io', 'ip', 'ir', 'is', 'it', 'iu',
'ja', 'je', 'ji', 'jo', 'ju',
'ka', 'ke', 'ki', 'ko', 'ku',
'la', 'le', 'li', 'lo', 'lu',
'ma', 'me', 'mi', 'mo', 'mu',
'na', 'ne', 'ni', 'no', 'nu',
'oa', 'ob', 'oc', 'od', 'oe', 'of', 'og', 'oi', 'oj', 'ok', 'ol', 'om', 'on', 'oo', 'op', 'or', 'os', 'ot', 'ou', 'ov', 'ow', 'ox', 'oz',
'pa', 'pe', 'pi', 'po', 'pu',
'qa', 'qe', 'qi', 'qo', 'qu',
'ra', 're', 'ri', 'ro', 'ru',
'sa', 'se', 'si', 'so', 'su',
'ta', 'te', 'ti', 'to', 'tu',
'wa', 'we', 'wi', 'wo', 'wu',
'xa', 'xe', 'xi', 'xo', 'xu',
'ya', 'ye', 'yi', 'yo', 'yu',
'za', 'ze', 'zi', 'zo'
];
let prefix = prefixes[Math.floor(Math.random() * prefixes.length)];
const suffix = suffixes[Math.floor(Math.random() * suffixes.length)];
@ -18,7 +43,7 @@ export function generateCityName(settings : cityGeneratorSetting) {
generatedName = capitalizeFirstLetter(generatedName);
prefix = capitalizeFirstLetter(prefix);
return numSyllables > 2 ? `${prefix} ${generatedName}` : `${generatedName}${suffix}`;
return numSyllables > 3 ? `${prefix} ${generatedName}` : `${generatedName}${suffix}`;
}
function capitalizeFirstLetter(string:string) {

View file

@ -1,4 +1,4 @@
import { drinkGeneratorSettings } from "main";
import { drinkGeneratorSettings } from "settings/Datatypes";
export function generatorDrinks(settings: drinkGeneratorSettings) {
const adjectives = settings.adj;

47
generators/dungeon.ts Normal file
View file

@ -0,0 +1,47 @@
import { dungeonGenSettings } from "settings/Datatypes";
export function generateDungeonName(settings: dungeonGenSettings): string {
const prefix: string[] = settings.dungeonTypes;
const adjective: string[] = settings.adjectives;
const noun: string[] = settings.nouns;
const locations: string[] = settings.locations;
const randomDesc: string[] = settings.randomDesc;
const prefixIndex = Math.floor(Math.random() * prefix.length);
const adjIndex = Math.floor(Math.random() * adjective.length);
const locIndex = Math.floor(Math.random() * locations.length);
const randomDescIndex = Math.floor(Math.random() * randomDesc.length);
const nounIndex = Math.floor(Math.random() * noun.length);
const usePrefix = Math.random() > 0.5;
let result;
if (usePrefix) {
result = {
name: `${prefix[prefixIndex]} of the ${adjective[adjIndex]} ${noun[nounIndex]}`,
description: generateDungeonDescription(locations[locIndex], prefix[prefixIndex], randomDesc[randomDescIndex])
};
} else {
result = {
name: `The ${adjective[adjIndex]} ${noun[nounIndex]}`,
description: generateDungeonDescription(locations[locIndex], prefix[prefixIndex], randomDesc[randomDescIndex])
}
}
return `${result.name}\nDescription: ${result.description}`
}
function generateDungeonDescription(location: string, dungeonType: string, randomDesc: string): string {
const templates = [
`Located in ${location}, this ${dungeonType} is known for ${randomDesc}.`,
`A ${dungeonType} that is known for ${randomDesc}.`,
`In the heart of ${location} lies this ${dungeonType}, notorious for ${randomDesc}.`,
`Deep within ${location}, the ${dungeonType} is feared for its ${randomDesc}.`,
`This ${dungeonType} located in ${location} is infamous for its ${randomDesc}.`,
`The ${dungeonType} in ${location} is a place to be reckoned with, famous for its ${randomDesc}.`
];
const templateIndex = Math.floor(Math.random() * templates.length);
return templates[templateIndex];
}

View file

@ -1,4 +1,4 @@
import { groupGenSettings } from "main";
import { groupGenSettings } from "settings/Datatypes";
export function generatorGroups(settings:groupGenSettings) {
const adjectives = settings.adj;

View file

@ -1,4 +1,4 @@
import { innGeneratorSettings } from "main";
import { innGeneratorSettings } from "settings/Datatypes";
interface Inn {
name: string;
description: string;

View file

@ -1,91 +1,64 @@
import { currency, lootTables } from "main";
import { currency, lootTables } from "settings/Datatypes";
export function generateLoot(enableCurrency: boolean, currencyFrequency: number, currencyTypes: currency[], lootTable: lootTables) {
const adjectives = lootTable.adj;
const nouns = lootTable.nouns;
const ItemAmount = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
const { adj, items } = lootTable;
const itemAmount = Math.floor(Math.random() * 5) + 1;
let loot = '';
for (let index = 0; index < ItemAmount; index++) {
const randomAdjective = adjectives[Math.floor(Math.random() * adjectives.length)];
for (let index = 0; index < itemAmount; index++) {
const randomAdjective = adj[Math.floor(Math.random() * adj.length)];
const amount = generateRareHighNumber(50, 0.1);
const vowels = ["a", "e", "i", "o", "u"];
const randomNoun = nouns[Math.floor(Math.random() * nouns.length)];
const vowelOrNot = isFirstCharInArray(vowels, randomAdjective) ? "an" : "a";
let addS = randomNoun;
if (!(randomNoun[randomNoun.length-1] === "e") && !(randomNoun[randomNoun.length] === "s")) {
addS = randomNoun[randomNoun.length] === "s" ? randomNoun + "'s" : randomNoun + "s";
}
amount > 1 ? loot += `${amount} ${randomAdjective} ${addS}` : loot += `${vowelOrNot} ${randomAdjective} ${randomNoun}`;
loot += ", "
const randomNoun = getRandomElement(items);
const article = /^[aeiou]/i.test(randomAdjective) ? 'an' : 'a';
const plural = randomNoun?.endsWith('s') ? `${randomNoun}'` : `${randomNoun}s`;
loot += `${amount > 1 ? `${amount} ${randomAdjective} ${plural}` : `${article} ${randomAdjective} ${randomNoun}`}, `;
}
if (enableCurrency) {
let currencyLoot = '';
const shouldGenCurrency = Math.floor(Math.random() * 100);
if (shouldGenCurrency < currencyFrequency) {
currencyTypes.forEach(element => {
const shouldGenCurrency = Math.random() * 100;
const currencyLoot = currencyTypes
.map((element) => {
const randomCurrencyAmount = generateRareHighNumberByRarity(element.rarity);
if (randomCurrencyAmount > 0) {
currencyLoot += randomCurrencyAmount + " " + element.name + ", ";
}
});
}
return randomCurrencyAmount > 0 ? `${randomCurrencyAmount} ${element.name}, ` : '';
})
.join('');
loot += currencyLoot;
if (shouldGenCurrency < currencyFrequency) {
loot += currencyLoot;
}
}
return loot;
return loot.slice(0, -2);
}
function isFirstCharInArray(array: string[], string: string) {
return array.includes(string[0]);
}
function generateRareHighNumber(maxNumber: number, rarityFactor: number) {
const randomNumber = Math.random();
if (randomNumber < rarityFactor) {
return Math.floor(Math.random() * maxNumber);
} else {
return Math.floor(Math.random() * (maxNumber / 10));
}
const rarity = randomNumber < rarityFactor ? rarityFactor : rarityFactor / 10;
return Math.floor(Math.random() * maxNumber * rarity);
}
function generateRareHighNumberByRarity(rarity: string) {
let rarityFactor = 0;
let maxNumber = 0;
const rarityFactors: { [key: string]: number } = { common: 0.7, uncommon: 0.5, rare: 0.2, rarest: 0.02 };
const maxNumbers: { [key: string]: number } = { common: 300, uncommon: 150, rare: 30, rarest: 10 };
const randomNumber = Math.random();
const isZero = Math.random();
if (rarity === "common" && isZero > 0.3) {
rarityFactor = 0.7;
maxNumber = 300;
}
if (rarity === "uncommon" && isZero > 0.5) {
rarityFactor = 0.5;
maxNumber = 150;
}
if (rarity === "rare" && isZero > 0.8) {
rarityFactor = 0.2
maxNumber = 30
}
if (rarity === "rarest" && isZero > 0.98) {
rarityFactor = 0.02
maxNumber = 10
}
if (rarityFactor === 0) {
if (randomNumber > rarityFactors[rarity] || rarityFactors[rarity] === undefined) {
return 0;
}
if (randomNumber < rarityFactor) {
return Math.floor(Math.random() * maxNumber);
} else {
return Math.floor(Math.random() * (maxNumber / 10));
return Math.floor(Math.random() * maxNumbers[rarity]);
}
function getRandomElement<T>(arr: { item: T, weight: number }[]): T | undefined {
const totalWeight = arr.reduce((acc, cur) => acc + cur.weight, 0);
let randomWeight = Math.random() * totalWeight;
for (const { item, weight } of arr) {
if (randomWeight < weight) {
return item;
}
randomWeight -= weight;
}
return undefined;
}

23
generators/plothook.ts Normal file

File diff suppressed because one or more lines are too long

495
generators/tradingPost.ts Normal file
View file

@ -0,0 +1,495 @@
import { rollD100, rollD20, weightedRandomItem } from "settings/Datatypes";
//Inspiration for this Generator Was taken from Spectactular Settlements Published By Nord Games. https://nordgamesllc.com/product/spectacular-settlements/ Please Buy the Book if you like this Generator.
const specialtyOptions: string[] = ["Atypical Shipping Methods", "Food & Drink", "Hospitality", "Information", "Purchasing Connections", "Unscrupulous Contractors"];
const ageOptions: { string: string, range: number[] }[] = [
{ string: "Established", range: [4, 8] },
{ string: "Mature", range: [9, 13] },
{ string: "Old", range: [14, 17] },
{ string: "Recently Established", range: [1, 3] },
{ string: "Ancient", range: [18, 19] },
{ string: "Unknown", range: [20, 20] },
];
const conditionOptions: { string: string, range: number[] }[] = [
{ string: "Ramshackled", range: [1, 2] },
{ string: "Poor", range: [3, 6] },
{ string: "Fair", range: [7, 14] },
{ string: "Good", range: [15, 18] },
{ string: "Immaculate", range: [19, 20] },
];
const visitorTrafficOptions: { string: string, range: number[] }[] = [
{ string: "Vacant: No one is really visiting.", range: [1, 2] },
{ string: "Groups: Visitors are a rarity, though a few might be around.", range: [3, 6] },
{ string: "Crowds: It's typical to see new visitors most days.", range: [7, 14] },
{ string: "Droves: New people come in and out of this trading post.", range: [15, 18] },
{ string: "Masses: The post is swarming with faces that would not be deemed as familiar.", range: [19, 20] },
];
const sizeOptions: { string: string, range: number[] }[] = [
{ string: "Tiny", range: [1, 2] },
{ string: "Small", range: [3, 6] },
{ string: "Medium", range: [7, 14] },
{ string: "Large", range: [15, 18] },
{ string: "Very Large", range: [19, 20] },
];
const environmentOptions: { string: string, range: number[] }[] = [
{ string: "Mountainous", range: [1, 2] },
{ string: "Desert", range: [3, 4] },
{ string: "Valley", range: [5, 6] },
{ string: "Swamp", range: [7, 8] },
{ string: "Plains", range: [9, 10] },
{ string: "Coastal", range: [11, 12] },
{ string: "Forest", range: [13, 14] },
{ string: "River", range: [15, 16] },
{ string: "Tundra", range: [17, 18] },
{ string: "Underground", range: [19, 20] }
];
const residentPopulationOptions: { string: string, range: number[] }[] = [
{ string: "Nearly Deserted", range: [1, 2] },
{ string: "Sparse", range: [3, 6] },
{ string: "Comfortable", range: [7, 14] },
{ string: "Congested", range: [15, 18] },
{ string: "Overwhelmed", range: [19, 20] },
];
const visitorDispositionOptions: { string: string, range: number[] }[] = [
{ string: "Hostile", range: [1, 2] },
{ string: "Unfriendly", range: [3, 6] },
{ string: "Neutral", range: [7, 14] },
{ string: "Friendly", range: [15, 18] },
{ string: "Open", range: [19, 20] },
];
const lawEnforcementOptions = [
{ string: "None", range: [1, 2] },
{ string: "Sheriff", range: [3, 6] },
{ string: "Local Watch", range: [7, 14] },
{ string: "Well-equipped", range: [15, 18] },
{ string: "Overwhelmingly Present", range: [19, 20] },
];
const leadershipOptions: { string: string, range: number[] }[] = [
{ string: "No Leader", range: [1, 1] },
{ string: "Hereditary", range: [2, 4] },
{ string: "Merchant Monarch", range: [5, 7] },
{ string: "Underworld or Criminal", range: [8, 10] },
{ string: "Oligarchy", range: [11, 13] },
{ string: "Local Council", range: [14, 16] },
{ string: "Single Elected Leader", range: [17, 19] },
{ string: "Commune", range: [20, 20] }
];
const wealthOptions: { string: string, range: number[] }[] = [
{ string: "Destitute", range: [1, 2] },
{ string: "Impoverished", range: [3, 6] },
{ string: "Average", range: [7, 14] },
{ string: "Prosperous", range: [15, 17] },
{ string: "Wealthy", range: [18, 19] },
{ string: "Affluent", range: [20, 20] }
];
const crimeOptions: { string: string, range: number[] }[] = [
{ string: "Regular", range: [1, 2] },
{ string: "Common", range: [3, 6] },
{ string: "Average", range: [7, 14] },
{ string: "Uncommon", range: [15, 18] },
{ string: "Rare", range: [19, 20] }
];
const shopOptions: { string: string, range: number[] }[] = [
{ string: "Baker", range: [1, 4] },
{ string: "Butcher", range: [5, 8] },
{ string: "Cooper", range: [9, 12] },
{ string: "Carpenter", range: [13, 16] },
{ string: "General Store", range: [17, 24] },
{ string: "Herbalist", range: [25, 28] },
{ string: "Smithy", range: [29, 36] },
{ string: "Tailor", range: [37, 40] },
{ string: "Tanner", range: [41, 44] },
{ string: "Thatcher", range: [45, 48] },
{ string: "Wainwright", range: [49, 52] },
{ string: "Weaver", range: [53, 56] },
{ string: "Alchemist", range: [57, 59] },
{ string: "Artist", range: [60, 62] },
{ string: "Bank/Exchange", range: [63, 65] },
{ string: "Cobbler", range: [66, 68] },
{ string: "Foundry", range: [69, 71] },
{ string: "Mill", range: [72, 74] },
{ string: "Textile Production", range: [75, 77] },
{ string: "Shipwright", range: [78, 80] },
{ string: "Rare Botanicals", range: [81, 82] },
{ string: "Luxury Furnishings", range: [83, 84] },
{ string: "Rare Trade Goods", range: [85, 86] },
{ string: "Rare Drink Brewery", range: [87, 88] },
{ string: "Magic Shop-Armor", range: [89, 90] },
{ string: "Magic Shop-Books", range: [91, 92] },
{ string: "Magic Shop-Clothing", range: [93, 94] },
{ string: "Magic Shop-Jewelry", range: [95, 96] },
{ string: "Magic Shop-Weapons", range: [97, 98] },
{ string: "Magic Shop-Miscellaneous & Curiosities", range: [99, 100] }
];
const serviceOptions: { string: string, range: number[] }[] = [
{ string: "Barber", range: [1, 8] },
{ string: "Bathhouse", range: [9, 16] },
{ string: "Doctor/Apothercary", range: [17, 24] },
{ string: "House of Leisure (GM Discretion)", range: [25, 32] },
{ string: "Inn", range: [33, 44] },
{ string: "Club", range: [45, 52] },
{ string: "Soothsayer", range: [53, 60] },
{ string: "Stable", range: [61, 68] },
{ string: "Tavern", range: [69, 80] },
{ string: "Hired Help - Muscle", range: [81, 82] },
{ string: "Hired Help - Assassins/Thieves", range: [83, 84] },
{ string: "Hired Help - Ranged Attack Specialists", range: [85, 86] },
{ string: "Hired Help - Scribes and Clerks", range: [87, 88] },
{ string: "Hired Help - Caravans and Mounts", range: [89, 90] },
{ string: "Hired Help - Arcane Academics/Inventors", range: [91, 92] },
{ string: "Hired Help - Magic Mercs", range: [93, 94] },
{ string: "Hired Help - Religious Guidance", range: [95, 96] },
{ string: "Hired Help - Divine Specialists", range: [97, 98] },
{ string: "Hired Help - Guides and Trackers", range: [99, 100] }
];
const origins: string[] = [
"Accidental: 'the trading post came about due to an accident, such as a caravan breaking down or mistaken directions. What was set up to deal with the eventually become the trading post.'",
"Business Venture: 'The trading post was established by a wealthy entrepreneur specifically to be a trading post from the start.'",
"Crossroads: 'The trading post is at the intersection of more than one major trade route.'",
"Military Outpost: 'The trading post was built on the remnants of an old fortress or watchtower, the structures of which have long since fallen down or been repurposed by the locals.'",
"No Man's Land: 'The trading post was established as a neutral place where opposing forces could purchase wares, without encroaching on enemy territory.'",
"Native: 'The trading post was started by someone native to the area, who saw potential in trade with passersby.'",
"Overnight Stop: 'The trading post was originally a single, large house for overnight stays for weary travellers, which soon grew, along with the demand for accommodations.'",
"Wilderness Expert: 'The trading post was started when a trapper, hunter or guide set up a camp, in order to aid those passing through the area.'",
"Religious: 'The trading post was established by a religious order, as a means of supporting their ministry.'",
"River Crossing: 'The trading post was built near a major river crossing so that traders could more easily cross and barter their goods.'",
"Pilgrimage: 'The trading post was set up to serve the needs of people travelling on a pilgrimage.'",
"King's Grant: 'The trading post was established as part of a royal grant, as a means of encouraging trade and commerce in the region.'",
"Scavengers: 'The trading post was created by a group of scavengers, who had discovered a valuable resource or sought to capitalize on the needs of travellers.'",
"Fishing Group: 'The trading post was established by a Group of Fishermen, in order to support a nearby population and capitalize on the sea trade.'",
"Frontier Expansion: 'The trading post was established as part of a larger effort to expand the kingdom's frontier, and to open up new trade routes.'"
];
export function generateTradingPost(): string {
let visitorTrafficMod = 0;
let popWealth = 0;
let sizeMod = 0;
let crimeMod = 0;
const origin = origins[Math.floor(Math.random() * origins.length)];
const specialiaty = specialtyOptions[Math.floor(Math.random() * specialtyOptions.length)];
const age = ageRoll();
visitorTrafficMod += age.mod;
const condition = conditionRoll();
popWealth += condition.mod;
const visitorTraffic = visitorTrafficRoll(visitorTrafficMod);
sizeMod += visitorTraffic.mod[0];
crimeMod += visitorTraffic.mod[1];
const postSize = weightedRandomItem(sizeOptions, rollD20(sizeMod));
const environment = weightedRandomItem(environmentOptions, rollD20(0));
const residentPop = residentPopRoll();
crimeMod += residentPop.mod;
const visitorDisposition = weightedRandomItem(visitorDispositionOptions, rollD20(0));
const lawEnforcement = lawEnforcementRoll();
crimeMod += lawEnforcement.mod;
const leadership = leadershipRoll();
const wealth = wealthRoll(popWealth);
crimeMod += wealth.mod;
const crime = weightedRandomItem(crimeOptions, rollD20(crimeMod));
const shops = shopRoll(postSize as string);
const services = serviceRoll(postSize as string);
return `Origin: ${origin}\nSpeciality: ${specialiaty}\nAge: ${age.string}\nCondition: ${condition.string}\nVisitor Traffic: ${visitorTraffic.string}\nTrading Post Size: ${postSize}\nEnvironment: ${environment}\nResident Population: ${residentPop.string}\nDisposition to Visitors: ${visitorDisposition}\nLaw Enforcement: ${lawEnforcement.string}\nLeadership: ${leadership}\nWealth: ${wealth.string}\nCrime: ${crime}\nShops: ${shops}\nServices: ${services}`
}
function serviceRoll(tradingPostSize: string): string {
let shopAmount = 0;
switch (tradingPostSize) {
case "Tiny":
shopAmount = Math.floor((Math.random() * 6) + 1);
break;
case "Small":
shopAmount = Math.floor((Math.random() * 6) + 1) + 1;
break;
case "Medium":
shopAmount = Math.floor((Math.random() * 6) + 1) + 3;
break;
case "Large":
shopAmount = Math.floor((Math.random() * 6) + 1) + 5;
break;
case "Very Large":
shopAmount = Math.floor((Math.random() * 6) + 1) + 7;
break;
default:
break;
}
const services: string[] = [];
for (let index = 0; index < shopAmount; index++) {
const roll: string = weightedRandomItem(serviceOptions, rollD100(0)) as string;
let hiredHelp = "";
if (roll.includes("Hired Help")) {
const helpSize = Math.floor((Math.random() * 12) + 1);
if (helpSize <= 6) {
hiredHelp = ": An Individual Person who is hiring out their services of this type";
}
if (helpSize <= 10) {
hiredHelp = ": A Team of people who are hiring out their services of this type";
} else {
hiredHelp = ": A Guild that is organised for this type of service "
}
}
services.push(`${roll + hiredHelp}`);
}
return generateStringWithCounts(services);
}
function shopRoll(tradingPostSize: string): string {
let shopAmount = 0;
switch (tradingPostSize) {
case "Tiny":
shopAmount = Math.floor((Math.random() * 8) + 1) + 2;
break;
case "Small":
shopAmount = Math.floor((Math.random() * 8) + 1) + 4;
break;
case "Medium":
shopAmount = Math.floor((Math.random() * 8) + 1) + 6;
break;
case "Large":
shopAmount = Math.floor((Math.random() * 8) + 1) + 8;
break;
case "Very Large":
shopAmount = Math.floor((Math.random() * 8) + 1) + 10;
break;
default:
break;
}
const shops: string[] = [];
for (let index = 0; index < shopAmount; index++) {
const roll: string = weightedRandomItem(shopOptions, rollD100(0)) as string;
shops.push(roll);
}
console.log(shops);
return generateStringWithCounts(shops);
}
function leadershipRoll(): string {
const roll: string = weightedRandomItem(leadershipOptions, rollD20(0)) as string;
let result = roll;
leadershipOptions.forEach(element => {
if (element.string === roll) {
if (element.string === leadershipOptions[4].string) {
const sway = Math.floor((Math.random() * 4) + 1);
switch (sway) {
case 1:
result = "Plutocracy (Merchant Group Runs the Post)";
break;
case 2:
result = "Magocracy (Mages and Magic users Run the Post)";
break;
case 3:
result = "Theocracy (Priests and Religious Orders Run the Post)";
break;
case 4:
result = "A Small unknown group Runs the Post";
break;
default:
break;
}
}
}
});
return result;
}
function ageRoll(): { string: string, mod: number } {
const roll: string = weightedRandomItem(ageOptions, rollD20(0)) as string;
if (roll === ageOptions[0].string) {
return { string: roll, mod: 0 }
}
if (roll === ageOptions[1].string) {
return { string: roll, mod: 1 };
}
if (roll === ageOptions[2].string) {
return { string: roll, mod: 2 };
}
if (roll === ageOptions[3].string) {
return { string: roll, mod: -1 };
}
if (roll === ageOptions[4].string) {
return { string: roll, mod: 3 };
}
return { string: roll, mod: 4 };
}
function wealthRoll(mod: number): { string: string, mod: number } {
const roll: string = weightedRandomItem(wealthOptions, rollD20(mod)) as string;
if (roll === ageOptions[0].string) {
return { string: roll, mod: -4 }
}
if (roll === ageOptions[1].string) {
return { string: roll, mod: -2 };
}
if (roll === ageOptions[2].string) {
return { string: roll, mod: 0 };
}
if (roll === ageOptions[3].string) {
return { string: roll, mod: -1 };
}
if (roll === ageOptions[4].string) {
return { string: roll, mod: -2 };
}
return { string: roll, mod: -4 };
}
function conditionRoll(): { string: string, mod: number } {
const roll: string = weightedRandomItem(conditionOptions, rollD20(0)) as string;
if (roll === ageOptions[0].string) {
return { string: roll, mod: -6 }
}
if (roll === ageOptions[1].string) {
return { string: roll, mod: -3 };
}
if (roll === ageOptions[2].string) {
return { string: roll, mod: 0 };
}
if (roll === ageOptions[3].string) {
return { string: roll, mod: 3 };
}
return { string: roll, mod: 6 };
}
function visitorTrafficRoll(mod: number): { string: string, mod: number[] } {
const roll: string = weightedRandomItem(visitorTrafficOptions, rollD20(mod)) as string;
if (roll === ageOptions[0].string) {
return { string: roll, mod: [0, 2] }
}
if (roll === ageOptions[1].string) {
return { string: roll, mod: [1, 1] };
}
if (roll === ageOptions[2].string) {
return { string: roll, mod: [2, 0] };
}
if (roll === ageOptions[3].string) {
return { string: roll, mod: [3, -1] };
}
return { string: roll, mod: [4, -2] };
}
function residentPopRoll(): { string: string, mod: number } {
const roll: string = weightedRandomItem(residentPopulationOptions, rollD20(0)) as string;
if (roll === ageOptions[0].string) {
return { string: roll, mod: 2 }
}
if (roll === ageOptions[1].string) {
return { string: roll, mod: 1 };
}
if (roll === ageOptions[2].string) {
return { string: roll, mod: 0 };
}
if (roll === ageOptions[3].string) {
return { string: roll, mod: -1 };
}
return { string: roll, mod: -2 };
}
function lawEnforcementRoll(): { string: string, mod: number } {
const roll: string = weightedRandomItem(lawEnforcementOptions, rollD20(0)) as string;
if (roll === ageOptions[0].string) {
return { string: roll, mod: -8 }
}
if (roll === ageOptions[1].string) {
return { string: roll, mod: -4 };
}
if (roll === ageOptions[2].string) {
return { string: roll, mod: 0 };
}
if (roll === ageOptions[3].string) {
return { string: roll, mod: 4 };
}
return { string: roll, mod: 8 };
}
function generateStringWithCounts(arr: string[]): string {
const counts: Record<string, number> = {};
for (const item of arr) {
counts[item] = (counts[item] || 0) + 1;
}
let result = "";
for (const item in counts) {
const count = counts[item];
const itemString = count > 1 ? `${item}s` : item;
if (result === "") {
result = `${count} ${itemString}`;
} else {
result = `${result}, ${count} ${itemString}`;
}
}
return result;
}

619
main.ts
View file

@ -1,226 +1,78 @@
import { GeneratorModal } from 'modal';
import { App, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import { GeneratorModal } from 'editor/GeneratorModal';
import { MarkdownView, Notice, Plugin, Editor } from 'obsidian';
import { InlineGeneratorSuggester } from "editor/InlineGenerator";
import { FantasyPluginSettings, possibleOptions } from 'settings/Datatypes';
import { DEFAULT_SETTINGS } from 'settings/DefaultSetting';
import { SettingTab } from 'settings/SettingsTab';
// Remember to rename these classes and interfaces!
export default class FantasyPlugin extends Plugin {
settings: FantasyPluginSettings;
currentEditor: Editor | null = null;
export type currency = {
name: string,
rarity: string
}
export type groupGenSettings = {
adj: string[],
nouns: string[],
nounsP: string[],
groupTypes: string[],
singleDescriptors : string[]
}
export type lootTables = {
adj: string[]
nouns: string[];
}
export type drinkGeneratorSettings = {
adj : string[],
nouns : string[],
}
export type cityGeneratorSetting = {
prefixArray: string[],
suffixArray: string[]
}
export type innGeneratorSettings = {
prefixes: string[],
innType: string[],
nouns: string[],
desc: string[],
rumors: string[]
}
interface MyPluginSettings {
enableCurrency: boolean;
citySettings: cityGeneratorSetting;
currencyTypes: currency[];
currencyFrequency: number;
innSettings: innGeneratorSettings;
drinkSettings: drinkGeneratorSettings;
lootSettings: lootTables;
groupSettings: groupGenSettings;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
enableCurrency: false,
citySettings: {
prefixArray: ["camp", "castle", "east", "edge", "ever", "great", "mount", "new", "north", "red", "rose", "south", "west"],
suffixArray: ["wood", "avon", "bank", "bark", "barrow", "bay", "beach", "bell", "borough", "berg", "bourne", "broad", "bridge", "brook", "brough", "burgh", "burn", "bury", "by", "canyon", "caster", "chester", "cliffe", "combe", "cot", "cott", "cote", "cove", "creek", "croft", "crook", "dale", "den", "din", "dine", "don", "downs", "falls", "field", "fin", "flats", "ford", "fork", "gate", "grove", "gum", "ham", "harbour", "heights", "hill", "holm", "hurst", "ing", "kirk", "land", "lake", "latch", "lea", "leigh", "ley", "marsh", "mere", "minster", "mond", "mont", "more", "ness", "park", "pilly", "pine", "point", "pond", "ridge", "river", "rock", "sett", "side", "son", "stead", "stoke", "stone", "stow", "terrace", "thorpe", "ton", "tor", "town", "vale", "valley", "view", "village", "ville", "water", "well", "wharf", "wick", "wood", "worth"],
},
innSettings: {
prefixes: ["The Rusty", "The Cosy", "The Grand", "The Quiet", "The Friendly", "Bashur's", "Harmony", "Harmonic", "Bald Faced", "Black", "Grey", "Silver", "White", "Blue", "Purple", "Green", "The Ugly", "The Pretty", "Ye Ol' Fighting", "The Drunk", "One", "Two", "Three", "Four", "Five", "Busta", "The Terrified"],
innType: ["Inn", "Lodge", "Tavern", "Rest", "Stop"],
nouns: ["Phoenix", "Centaur", "Dragon", "Selkie", "Griffin", "Bandersnatch", "Mermaid", "Werewolf", "Dryad", "Golem", "Bugbear", "Goblin", "Tiger", "Cat", "Warrior", "Wizard", "Drop Bear", "Bear", "Lagoon", "Bunyip", "Rat King", "King's", "Automaton", "Beach", "Reaper", "Grim", "Ogre", "Skeleton", "Ghost"],
desc: [
"located in the heart of the city, surrounded by bustling marketplaces and busy streets.",
"nestled in a peaceful and serene countryside, with picturesque views of rolling hills and sprawling fields.",
"overlooking the sea, with panoramic views of the ocean and a nearby sandy beach.",
"situated in the heart of a dense forest, surrounded by towering trees and the chirping of birds.",
"located at the foot of a grand mountain, with stunning views of the rugged peaks and snow-capped summits.",
"perched on the edge of a cliff, with breathtaking views of the valley below and the distant horizon.",
"hidden away in a remote corner of the world, surrounded by untouched nature and wildlife.",
"tucked away in a hidden valley, with tranquil meadows and a crystal-clear lake.",
"perched on the top of a hill, with magnificent views of the city and the surrounding countryside.",
"set in a bustling harbour town, with the sound of boats and seagulls in the air.",
"located in a bustling port city, surrounded by the hustle and bustle of daily life.",
"nestled in the heart of a peaceful village, surrounded by rolling hills and lush greenery.",
"overlooking the ocean, with views of the horizon and a nearby pier.",
"settled deep in the heart of a mysterious jungle, with a cacophony of tropical sounds and vibrant life.",
"positioned at the edge of a desert, with sweeping views of the sand dunes and the distant horizon.",
"hidden away in a forgotten corner of the world, surrounded by ancient ruins and mysterious artifacts.",
"tucked away in a bustling city, with the sound of music and laughter in the air.",
"perched atop a tall mountain, with sweeping views of the countryside and a majestic waterfall.",
"set in a serene lake town, with magnificent views of the shimmering lake and the surrounding mountains.",
"located in the heart of a bustling market town, with the smell of spices and exotic foods wafting in the air.",
"nestled in a quiet corner of the countryside, surrounded by rolling hills and picturesque views.",
"overlooking a river, with stunning views of the cascading rapids and the lush riverbank.",
"situated in the heart of a dense forest, with the sound of birds singing and a canopy of trees.",
"located at the foot of a majestic mountain range, with breathtaking views of the snow-capped peaks and the distant horizon.",
"hidden away in a forgotten corner of the world, surrounded by untouched nature and mysterious creatures.",
"tucked away in a peaceful valley, with tranquil meadows and a babbling brook running nearby.",
"perched atop a large hill, with sweeping views of the surrounding countryside and a nearby lake.",
"set in a bustling harbour town, with the sound of waves and seagulls in the air.",
"located in an ancient city, surrounded by vibrant culture and the bustling of daily life.",
"nestled in the heart of a peaceful village, surrounded by rolling fields and lush greenery.",
"overlooking a bustling port town, with breathtaking views of the harbor and its many boats.",
"situated deep in the heart of a mysterious swamp, with a cacophony of strange sounds and vibrant wildlife.",
"positioned at the edge of a vast desert, with magnificent views of the sand dunes and the distant horizon.",
"hidden away in a secret corner of the world, surrounded by ancient ruins and magical artifacts.",
"tucked away in a bustling market town, with the smell of exotic spices and fresh produce in the air.",
"perched atop a steep cliff, with sweeping views of the valley and a nearby waterfall.",
"set in a tranquil mountain town, with magnificent views of the snow-capped peaks and the surrounding countryside.",
"located in the heart of a bustling city, surrounded by vibrant culture and the sound of music.",
"nestled in a peaceful corner of the countryside, surrounded by rolling hills and lush greenery.",
"overlooking a calm lake, with stunning views of the shimmering water and a nearby pier.",
"situated in the heart of a dense forest, with the sound of birdsong and a canopy of trees.",
"located at the foot of a grand mountain range, with breathtaking views of the rugged peaks and distant horizon.",
"hidden away in a forgotten corner of the world, surrounded by untouched nature and mysterious creatures.",
"tucked away in a hidden valley, with tranquil meadows and a crystal-clear stream.",
"perched atop a tall hill, with sweeping views of the surrounding countryside and a nearby lake.",
"set in a quaint harbour town, with the sound of waves and seagulls in the air.",
"located in the heart of an ancient city, surrounded by vibrant culture and the bustling of daily life.",
"nestled in a peaceful corner of the countryside, surrounded by rolling hills and picturesque views.",
"overlooking a bustling port town, with breathtaking views of the harbor and its many ships.",
"situated deep in the heart of a mysterious jungle, with a cacophony of tropical sounds and vibrant wildlife.",
"positioned at the edge of a vast desert, with magnificent views of the sand dunes and distant horizon.",
"hidden away in a secret corner of the world, surrounded by ancient ruins and mysterious artifacts.",
"tucked away in a bustling market town, with the smell of spices and exotic foods wafting in the air.",
"perched atop a steep cliff, with sweeping views of the valley and a majestic waterfall.",
"set in a serene mountain town, with magnificent views of the snow-capped peaks and the surrounding countryside.",
"located in a bustling port city, surrounded by the hustle and bustle of daily life.",
"nestled in a peaceful corner of the countryside, surrounded by rolling fields and lush greenery.",
"overlooking the sea, with panoramic views of the ocean and a nearby sandy beach.",
"situated in the heart of a dense forest, with the sound of birds singing and a canopy of trees.",
"located at the foot of a majestic mountain range, with breathtaking views of the rugged peaks and the distant horizon.",
"hidden away in a forgotten corner of the world, surrounded by untouched nature and mysterious creatures.",
"tucked away in a hidden valley, with tranquil meadows and a crystal-clear lake.",
],
rumors: [
"My niece told me about a fugitive found an old tomb when discovered a lake snake. And now defeated a superior foe in single combat.",
"My stepson told me about a monarchist found a magic item when discovered a vampire. And now the moon might fracture!.",
"They say that a religious emissary was seen with a drunk down near the merchant quarter and there was a lich. People heard it from a viking warrior, so it is probably just idle gossip.",
"Passers-by talk about the disappearance of someone. They mention a hidden fort said to house something truly abnormal, somewhere out by the waterfall. If asked further, people will tell you, it should be avoided at all cost. In addition a priest at a local temple asks the players to collect something from there.",
"People have heard that a disgraced executioner was seen with snake wine down near the mages guild and there was a hippogriff.",
"Believably a historical archivist was seen with a strange man from the inn down near the crafts guild and there was a soul gathering demon. People heard it from eighty-six pixies in a trench coat, so it is likely true.",
"Nailed to a tree is a small note with a warning to all about a dark park with the etchings of a dark ritual, somewhere in the catacombs. If asked further, people will tell you, people whove seen it are not the same. In addition a local shopkeeper hushes on the players and leads them to his/her home, when asked about the place.",
"When they want to scare the children, the locals tell a story of a dragon-tamer in the mountains was seen with an escaped convict down near the crafts guild and nearby there was a dead noble.",
"Apparently the local dragon has been cursed by a witch to ceaselessly wander through the forest, spontaneously combusting. People heard it from an old Guard, so it is probably true.",
"A rumor is circulating that a strange creature lurks in the depths of the nearby forest. It is said that it draws its strength from the shadows and that it can only be seen with the help of a special amulet.",
"Rumor has it that a royal knight was seen with a strange woman down near the druid grove and there was a banshee.",
"It is said that a lost city exists in the desert, full of treasures, guarded by a powerful being. People heard it from a strange old man at the market, so it is likely true.",
"The villagers talk of a witch that lives in the nearby swamp. It is said that she can be seen during the full moon, dancing around a fire in the night sky.",
"A rather silly rumour has been circulating that a powerful wizard has opened a portal to the underworld. People heard it from a mysterious traveller, so it is probably just idle gossip.",
"People whisper that a foreign prince has been in the area. It is said that he is searching for a magical artifact that will give him untold power.",
"The bards tell a tale of a powerful warrior who has laid claim to a cursed temple in the mountains. It is said that anyone who enters risks being trapped forever.",
"Word on the street is that a strange creature lurks in the sewers. It is said to be able to control the minds of lesser creatures and even humans.",
"People whisper that a powerful mage has been seen in the area. It is said that he is searching for an ancient artifact that will grant him immortality.",
"Rumors abound of a powerful dragon that protects a hidden cave somewhere in the mountains. It is said that anyone who enters must face the dragon in battle.",
"People have heard that a group of adventurers is on a quest for a magical gem. It is said that it will grant them great power and wealth.",
"The locals tell a story of a powerful vampire who rules a castle in the mountains. It is said that anyone who enters must face the vampire in battle.",
"They say that a mysterious stranger has been seen in the area. It is said that he is searching for a magical artifact that will grant him untold power.",
"People have heard that a powerful witch has opened a portal to the underworld. It is said that anyone who enters will be cursed for eternity.",
"The bards tell a tale of a powerful wizard who has laid claim to a haunted castle in the forest. It is said that anyone who enters risks his/her life.",
"Word on the street is that a strange creature is living in the sewers. It is said to be able to manipulate the minds of lesser creatures and even humans.",
"People whisper that a powerful necromancer has been seen in the area. It is said that he is searching for a powerful artifact that will give him domination over death.",
"Rumors abound of a powerful dragon that is guarding a hidden temple in the mountains. It is said that anyone who enters must face the dragon in single combat.",
"People have heard that a group of adventurers are on a quest for a magical amulet. It is said that it will give them great power and wealth.",
"The locals tell a story of a powerful warlock who rules a castle in the forest. It is said that anyone who enters must face the warlock in single combat.",
"They say that a mysterious figure has been seen in the area. It is said that he is searching for a magical item that will grant him ultimate power.",
"People have heard that a powerful witch has opened a portal to the spirit realm. It is said that anyone who enters will be cursed for all eternity.",
"The bards tell a tale of a powerful mage who has laid claim to an ancient temple in the mountains. It is said that anyone who enters risks being trapped forever.",
"Word on the street is that a strange creature lurks in the depths of the nearby lake. It is said to be able to control the minds of lesser creatures and even humans.",
"People whisper that a powerful sorcerer has been seen in the area. It is said that he is searching for a powerful relic that will give him control over the elements.",
"Rumors abound of a powerful dragon that is guarding a hidden city in the mountains. It is said that anyone who enters must face the dragon in single combat.",
"People have heard that a group of mercenaries are on a quest for a magical sword. It is said that it will grant them great power and wealth.",
"The locals tell a story of a powerful witch who rules a castle in the forest. It is said that anyone who enters must face the witch in single combat.",
"They say that a mysterious figure has been seen in the area. It is said that he is searching for a magical artifact that will grant him total power.",
"People have heard that a powerful wizard has opened a portal to the astral plane. It is said that anyone who enters will be cursed for eternity.",
"The bards tell a tale of a powerful necromancer who has laid claim to a haunted tower in the forest. It is said that anyone who enters risks his/her life.",
"Word on the street is that a strange creature is living in the sewers. It is said to be able to manipulate the minds of lesser creatures and even humans.",
"People whisper that a powerful warlock has been seen in the area. It is said that he is searching for a powerful relic that will give him mastery over death.",
"Rumors abound of a powerful dragon that protects a hidden shrine somewhere in the mountains. It is said that anyone who enters must face the dragon in battle.",
"People have heard that a group of adventurers are on a quest for a magical staff. It is said that it will grant them great power and wealth.",
"The locals tell a story of a powerful vampire who rules a castle in the mountains. It is said that anyone who enters must face the vampire in single combat.",
]
},
currencyTypes: [{
"name": "GP",
"rarity": "rare"
},
{
"name": "CP",
"rarity": "common"
},
{
"name": "SP",
"rarity": "common"
},
{
"name": "PP",
"rarity": "rarest"
}],
currencyFrequency: 50,
drinkSettings: {
adj: ["Almond", "Amazing", "Ancient", "Angel", "Angelic", "Apple", "Apricot", "Arctic", "Aromatic", "Autumn", "Avocado", "Balanced", "Banana", "Basil", "Bay Leaf", "Beautiful", "Beetroot", "Black", "Blue", "Blueberry", "Boiled", "Brilliant", "Brown", "Brutal", "Burning", "Calm", "Capital", "Caramel", "Catnip", "Cherry", "Cherry Blossom", "Chestnut", "Chilled", "Chilli", "Cinnamon", "Clouded", "Cloudy", "Coconut", "Cool", "Coriander", "Cosmic", "Cranberry", "Crazy", "Crimson", "Cucumber", "Demon", "Demonic", "Dire", "Eastern", "Easy", "Electric", "Elemental", "Evil", "Extreme", "Fainting", "Fallen", "Fancy", "Fantasy", "Fast", "Final", "First", "Flaming", "Flower", "Flying", "Forest", "Fresh", "Frosted", "Frozen", "Fruity", "Garlic", "Gentle", "Ginger", "Gingerroot", "Gleaming", "Glowing", "Grape", "Grapefruit", "Green", "Hazelnut", "High", "Holy", "Honest", "Honey", "Hot", "Hushed", "Icy", "Imaginary", "Incredible", "Infinite", "Innocent", "Insane", "Insanity", "Jasmine", "Kiwi", "Lavender", "Lavish", "Lemon", "Lemonade", "Lemongrass", "Lemony", "Lime", "Low", "Lucky", "Mad", "Mango", "Melon", "Mild", "Milk", "Milky", "Mint", "Minty", "Molten", "Mountain", "Mystic", "Nasty", "Nimble", "Noble", "Northern", "Noxious", "Numb", "Nutmeg", "Nutty", "Oak", "Oaken", "Oblivious", "Obvious", "Orange", "Oregano", "Palm", "Paranoid", "Passion Fruit", "Peacan", "Peanut", "Pear", "Peppermint", "Perfect", "Pineapple", "Pink", "Potato", "Precious", "Pure", "Rainbow", "Red", "River", "Rose", "Rose Petal", "Rosemary", "Rotten", "Rough", "Rude", "Rushed", "Saffron", "Salt 'n Pepper", "Salty", "Sanguine", "Savage", "Scented", "Secret", "Silent", "Smooth", "Southern", "Spearmint", "Spiced", "Spicy", "Spirit", "Spring", "Stale", "Steamy", "Sticky", "Strawberry", "Sugar", "Sugary", "Summer", "Surprised", "Sweet", "Tarragon", "Thyme", "Tiny", "Tomato", "Tropic", "Tropical", "Twisting", "Ultimate", "Unholy", "Universal", "Unlucky", "Vanilla", "Vanillabean", "Vibrant", "Warm", "Wasabi", "Watermelon", "Western", "Wet", "Whimsical", "Whipped", "White", "Wicked", "Wild", "Willow", "Winged", "Winter", "Wonderful", "Wonderous", "Yellow", "Spicy", "Fruity", "Sour", "Sweet", "Smooth", "Bitter", "Refreshing", "Amigo", "Arrow", "Ball", "Barrage", "Bear", "Blast", "Blaze", "Bliss", "Blitz", "Blizzard", "Blood", "Blossom", "Bolt", "Bomb", "Breeze", "Bruiser", "Bubble", "Bull", "Burst", "Buzzer", "Cooler", "Crash", "Critter", "Crush", "Crusher", "Crystal", "Delight", "Dog", "Double", "Drop", "Duke", "Dutchess", "Earthquake", "Eclipse", "Eight", "Enigma", "Eye", "Five", "Flash", "Fluff", "Fluffy", "Four", "Freedom", "Fury", "Giant", "Gloom", "Grog", "Heaven", "Hell", "Hopper", "Horn", "Horror", "Hound", "Howler", "Infusion", "Jam", "Joke", "Joker", "Joy", "Killer", "Kiss", "Kisses", "Knight", "Lady", "Lagoon", "Light", "Lion", "Lord", "Lotus", "Lover", "Major", "Minor", "Mix", "Monsoon", "Moonshine", "Mud", "Murder", "Nectar", "Night", "Nightfall", "Orb", "Paradise", "Paralyzer", "Parody", "Passion", "Pearl", "Pecker", "Petal", "Phantom", "Plus", "Pop", "Puff", "Punch", "Rage", "Riddle", "Roar", "Rumble", "Rush", "Score", "Scream", "Seven", "Shadow", "Shield", "Shot", "Shrub", "Silence", "Sip", "Six", "Sizzle", "Slammer", "Slap", "Slapper", "Sling", "Slingshot", "Slush", "Smash", "Smooch", "Snake", "Snowball", "Sour", "Special", "Squeeze", "Stardust", "Starlight", "Stinger", "Storm", "Striker", "Sunrise", "Sunset", "Surge", "Talon", "Teaser", "Temper", "Tempest", "Thrill", "Thriller", "Thunder", "Ticker", "Tickle", "Tonic", "Tornado", "Torrent", "Touch", "Tremor", "Twilight", "Twister", "Velour", "Velvet", "Vengeance", "Volcano", "Volley", "Wacker", "Walk", "Walker", "Wave", "Whisper", "Whistle", "Wink", "Wonder", "Zombie"],
nouns: ["Cocktail", "Smoothie", "Shake", "Juice", "Iced Tea", "Lemonade", "Soda", "Ale", "Brandy", "Tea", "Tea", "Sherry", "Brew", "Cappuchino", "Cider", "Coffee", "Cognac", "Dark Ale", "Dark Beer", "Drink", "Espresso", "Gin", "Java", "Lager", "Light Ale", "Light Beer", "Mead", "Mocha", "Red Wine", "Rum", "Sake", "Tea", "Tonic", "Vodka", "Whiskey", "White Wine", "Wine"]
},
lootSettings: {
adj: ["old", "tattered", "rotten", "shiny", "polished", "rusty", "broken", "priceless", "ancient", "precious"],
nouns: ["bag", "scroll", "book", "map", "key", "ring", "necklace", "potion", "ball bearing", "alchemists fire", "antitoxin", "caltrop", "book", "candle", "map scroll", "chain", "climbers kit", "crowbar", "fishing tackle", "holy water", "hunting trap", "lantern", "lock", "oil", "poison", "ram portable", "spyglass", "tent", "bucket", "glass bottle", "chest", "signet ring", "sealing wax", "whetstone", "arrows", "bolt", "censer", "dice set", "dragonchess set", "flute", "glass blowers tool", "holy oil", "lute", "playing card set", "sack", "saddle", "sovereign glue", "universal solvent", "prosthetic wooden arm", "hook hand", "peg leg", "glass eye", "bag of marbles", "hatchet", "alchemists supplies", "brewers supplies", "burglars pack", "lockpicks", "calligraphers supplies", "carpenter's tool", "cartographers tool", "chain mail", "cooks utensil", "disguise kit", "dungeoneers pack", "entertainers pack", "explorers pack", "forgery kit", "half plate", "healers kit", "ink", "ink pen", "parchment", "shovel", "leather worker's tool", "masons tool", "navigator's tool", "net", "painters supplies", "perfume", "plate armor", "potters tool", "priests pack", "ring mail", "scale mail", "scholar's pack", "scimitar", "shield", "whistle", "smiths tool", "thieves tool", "torch", "weaver's tool", "cobblers tool", "jewelers tools", "tinkers tool", "poisoners kit", "herbalism kit", "bell", "block and tackle", "animal or pet", "traveler's clothes", "fine clothes"]
},
groupSettings: {
adj: ["azure", "black", "blue", "brass", "bronze", "brown", "cardinal", "cobalt", "copper", "crimson", "crystal", "demon", "denim", "diamond", "ebony", "electric", "emerald", "fire", "flame", "gold", "green", "grey", "grizzly", "ice", "ivory", "jade", "onyx", "orange", "red", "royal", "ruby", "sanguine", "sapphire", "scarlet", "thunder", "violet", "white", "yellow", "", "", "", "", "", "", "", "", "", "", "", ""],
nouns: ["alien", "alligator", "angel", "badger", "banner", "bat", "bear", "blood", "blooddrop", "blossom", "boar", "bull", "bulldog", "butterfly", "chainsaw", "cobra", "coyote", "crocodile", "cross", "crow", "death", "demon", "devil", "dragon", "dragonfly", "dragontooth", "dwarf", "eagle", "elephant", "enigma", "fang", "forsaken", "ghost", "gorilla", "hand", "hog", "honey badger", "horn", "jackal", "knife", "knuckle", "leopard", "lily", "lion", "liontooth", "mamba", "mammoth", "monkey", "moth", "needle", "owl", "phantom", "pygmy", "pincer", "pistol", "rat", "raven", "ravenclaw", "razor", "reaper", "rebel", "rider", "rose", "saber", "sabortooth", "serpent", "shark", "sharkfin", "sharktooth", "skeleton", "skull", "snake", "spider", "sword", "tear", "thorn", "tiger", "toad", "troll", "undead", "viper", "vulture", "warthog", "water", "wolf", "wolverine"],
nounsP: ["aliens", "alligators", "angels", "badgers", "bats", "bears", "blooddrops", "bloods", "blossoms", "boars", "bulldogs", "bulls", "butterflies", "chainsaws", "cobras", "coyotes", "crocs", "crosses", "crows", "demons", "devils", "dragonflies", "dragons", "dwarves", "eagles", "elephants", "enigmas", "fangs", "forsaken", "ghosts", "gorillas", "growlers", "hogs", "honey badgers", "horns", "jackals", "knives", "knuckles", "leopards", "lilies", "lions", "mambas", "mammoths", "monkeys", "moths", "needles", "owls", "phantoms", "pigmies", "pillagers", "pincers", "pistols", "plunderers", "rats", "ravenclaws", "ravens", "razors", "reapers", "rebels", "riders", "roses", "sabors", "seals", "serpents", "sharkfins", "sharks", "sharkteeth", "skeletons", "skulls", "slicers", "snakes", "spiders", "swords", "takers", "tears", "thorns", "tigers", "toads", "trolls", "undead", "vipers", "vultures", "warthogs", "wolverines", "wolves"],
groupTypes: ["association", "band", "brotherhood", "clan", "company", "crew", "gang", "posse", "riders", "soldiers", "squad", "syndicate", "tribe"],
singleDescriptors: ["abandoned", "anarchists", "anonymous", "chargers", "damnation", "day walkers", "dead eyes", "destroyers", "disciples", "doom bringers", "dreamers", "liberated", "liberation front", "empty eyes", "eternals", "faceless ones", "fallen angels", "forsaken", "grim reapers", "hopeless", "hopeless ones", "hunters", "idealists", "immortals", "invincibles", "invisibles", "kings", "life takers", "loners", "men of limbo", "men of the night", "women of limbo", "women of the night", "mob", "nameless", "night stalkers", "poison ivies", "purgatory", "ravagers", "risen demons", "salvation", "shadows", "silence", "silent death", "silent footsteps", "soul stealers", "soulless ones", "united front", "unseen", "untamed", "voiceless ones", "void", "whisperers", "wild ones", "wildlings"]
//Function used to return the array of options for the suggester.
getOptionsForSuggest(): string[] {
return possibleOptions;
}
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('book', 'Fantasy Generators', (evt: MouseEvent) => {
this.app.workspace.on('active-leaf-change', (leaf) => {
if (leaf) {
const view = leaf.view;
if (view instanceof MarkdownView) {
this.currentEditor = view.editor;
} else {
this.currentEditor = null;
}
} else {
this.currentEditor = null;
}
});
//Command to open Modal dialog
this.addCommand({
id: 'open-fantasy-generator',
name: 'Open Fantasy Generator',
callback: () => {
new GeneratorModal(this.app, (result) => {
const copyContent = async () => {
//Try to see if any generators spit out an Error or if copying the string fails.
try {
if (result instanceof Error) {
new Notice(`${result}`);
} else {
await navigator.clipboard.writeText(result);
new Notice(`${result} was copied to the clipboard.`);
}
} catch (err) {
console.error('Failed to copy: ', err);
new Notice("Failed to copy, Check error in console.");
}
}
copyContent();
}, this).open();
},
});
//Register the InlineGeneratorSuggester to the Editor suggester.
this.registerEditorSuggest(new InlineGeneratorSuggester(this.getOptionsForSuggest, this));
// This creates an icon in the left ribbon to access the modal for the Fantasy Content Generator.
this.addRibbonIcon('book', 'Fantasy Generators', (evt: MouseEvent) => {
// Called when the user clicks the icon.
//this.activateView();
new GeneratorModal(this.app, (result) => {
const copyContent = async () => {
//Try to see if any generators spit out an Error or if copying the string fails.
try {
await navigator.clipboard.writeText(result);
new Notice(`${result} was copied to the clipboard.`);
if (result instanceof Error) {
new Notice(`${result}`);
} else {
await navigator.clipboard.writeText(result);
new Notice(`${result} was copied to the clipboard.`);
}
} catch (err) {
console.error('Failed to copy: ', err);
new Notice("Failed to copy, Check error in console.");
@ -231,20 +83,11 @@ export default class MyPlugin extends Plugin {
}, this).open();
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
this.addSettingTab(new SettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
console.log("loaded Fantasy Content Generator");
}
onunload() {
@ -259,333 +102,3 @@ export default class MyPlugin extends Plugin {
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
convertStringToArray(string:string, arr:string[]): void {
//const newString = string.replace(/\s/g, '');
const array = string.split(',');
array.forEach((el) => {
arr.push(el);
})
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createSettingsBlock(containerEl: HTMLElement, textA: string, arr: any[], type: string): void {
new Setting(containerEl)
.setName("New Addition:")
.addTextArea((text) => {
text.onChange((value) => {
textA = value;
})
})
.addButton((btn) => {
btn.setCta().setButtonText("Add")
.onClick(async () => {
this.convertStringToArray(textA, arr);
this.display();
await this.plugin.saveSettings();
})
})
containerEl.createEl("p", { text: "Click 'remove' on a prefix you would like to removed" });
const foldDiv = containerEl.createEl('details',{cls: "OFCGDetails"});
foldDiv.createEl("summary", { text: type, cls: "OFCGSummary" });
for (let index = 0; index < arr.length; index++) {
new Setting(foldDiv)
.setName(arr[index])
.addButton((btn) => btn
.setCta()
.setButtonText("Remove")
.onClick(async() => {
arr.splice(index, 1);
this.display();
await this.plugin.saveSettings();
})
)
}
containerEl.createEl('hr');
}
display(): void {
const {containerEl} = this;
containerEl.empty();
containerEl.createEl('h1', { text: 'Fantasy Content Generator' });
new Setting(containerEl)
.setName('Reset To Defaults')
.setDesc('Click if you would like to use the default settings again')
.addButton((btn) => {
btn.setCta()
.setButtonText("Reset")
.onClick(async() => {
this.plugin.settings = DEFAULT_SETTINGS;
this.display();
await this.plugin.saveSettings();
})
})
// CURRENCEY SETTINGS //
containerEl.createEl("h2", { text: "Currency Settings" });
new Setting(containerEl)
.setName('Enable Currency for Loot Generation.')
.setDesc('If you have Currency in your World or game consider Activating this')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.enableCurrency);
toggle.onChange(async (value) => {
this.plugin.settings.enableCurrency = value;
this.display();
await this.plugin.saveSettings();
})
})
if (this.plugin.settings.enableCurrency) {
new Setting(containerEl).setName("Occurance Rate:").setDesc("Set How Frequently Loot generates currency as a percentage of 100")
.addText((text) => {
text.setValue(String(this.plugin.settings.currencyFrequency));
text.onChange(async(value) => {
if (!(isNaN(+value))) {
this.plugin.settings.currencyFrequency = Number(value);
await this.plugin.saveSettings();
}
})
})
const ctext = {
name: '',
rarity: 'common'
}
new Setting(containerEl)
.setName("Currency Name:")
.addText((text) => {
text.onChange((value) => {
ctext.name = value;
})
}).addDropdown((drop) => {
drop.addOption("common", "Common");
drop.addOption("uncommon", "Uncommon");
drop.addOption("rare", "Rare");
drop.addOption("rarest", "Rarest");
drop.onChange((value) => {
ctext.rarity = value;
})
})
.addButton((btn) => {
btn.setCta().setButtonText("Add")
.onClick(async () => {
this.plugin.settings.currencyTypes.push(ctext);
this.display();
await this.plugin.saveSettings();
})
})
containerEl.createEl("h4", { text: "Added Currency" });
containerEl.createEl("p", { text: "Click remove on a currency you would like to removed" });
const foldDiv = containerEl.createEl('details',{cls: "OFCGDetails"});
foldDiv.createEl("summary", { text: "Currency", cls: "OFCGSummary" });
for (let index = 0; index < this.plugin.settings.currencyTypes.length; index++) {
new Setting(foldDiv)
.setName(this.plugin.settings.currencyTypes[index].name)
.addButton((btn) => btn
.setCta()
.setButtonText("Remove")
.onClick(async() => {
this.plugin.settings.currencyTypes.splice(index, 1);
this.display();
await this.plugin.saveSettings();
})
)
}
}
// END CURRENCY SETTINGS //
containerEl.createEl('hr');
//SETTLEMENT SETTINGS//
containerEl.createEl("h2", { text: "Settlement Settings" });
let preText = "";
let sufText = "";
containerEl.createEl("h4", { text: "Prefixes being used" });
new Setting(containerEl)
.setName("New Prefix:")
.addTextArea((text) => {
text.onChange((value) => {
preText = value;
})
})
.addButton((btn) => {
btn.setCta().setButtonText("Add")
.onClick(async () => {
this.convertStringToArray(preText, this.plugin.settings.citySettings.prefixArray);
this.display();
await this.plugin.saveSettings();
})
})
containerEl.createEl("p", { text: "Click 'remove' on a prefix you would like to removed" });
const foldDiv = containerEl.createEl('details',{cls: "OFCGDetails"});
foldDiv.createEl("summary", { text: "Prefixes", cls: "OFCGSummary" });
for (let index = 0; index < this.plugin.settings.citySettings.prefixArray.length; index++) {
new Setting(foldDiv)
.setName(this.plugin.settings.citySettings.prefixArray[index])
.addButton((btn) => btn
.setCta()
.setButtonText("Remove")
.onClick(async() => {
this.plugin.settings.citySettings.prefixArray.splice(index, 1);
this.display();
await this.plugin.saveSettings();
})
)
}
containerEl.createEl('hr');
containerEl.createEl("h4", { text: "Suffixes being used" });
new Setting(containerEl)
.setName("New Suffix:")
.addTextArea((text) => {
text.onChange((value) => {
sufText = value;
})
})
.addButton((btn) => {
btn.setCta().setButtonText("Add")
.onClick(async () => {
this.convertStringToArray(sufText, this.plugin.settings.citySettings.suffixArray);
this.display();
await this.plugin.saveSettings();
})
})
containerEl.createEl("p", { text: "Click 'remove' on a suffix you would like to removed" });
const foldDiv2 = containerEl.createEl('details',{cls: "OFCGDetails"});
foldDiv2.createEl("summary", { text: "Suffixes", cls: "OFCGSummary" });
for (let index = 0; index < this.plugin.settings.citySettings.suffixArray.length; index++) {
new Setting(foldDiv2)
.setName(this.plugin.settings.citySettings.suffixArray[index])
.addButton((btn) => btn
.setCta()
.setButtonText("Remove")
.onClick(async() => {
this.plugin.settings.citySettings.suffixArray.splice(index, 1);
this.display();
await this.plugin.saveSettings();
})
)
}
// END SETTLEMENT SETTINGS //
containerEl.createEl('hr');
// INN'S / TAVERN SETTINGS //
containerEl.createEl("h2", { text: "Inn & Tavern Settings" });
const innPreText = "";
const innTypeText = "";
const innNounText = "";
const innDescText = "";
const innRumorText = "";
containerEl.createEl("h4", { text: "Prefixes being used" });
this.createSettingsBlock(containerEl, innPreText, this.plugin.settings.innSettings.prefixes, "Prefixes");
containerEl.createEl("h4", { text: "Type's being used" });
this.createSettingsBlock(containerEl, innTypeText, this.plugin.settings.innSettings.innType, "Type's");
containerEl.createEl("h4", { text: "Nouns being used" });
this.createSettingsBlock(containerEl, innNounText, this.plugin.settings.innSettings.nouns, "Nouns");
containerEl.createEl("h4", { text: "Description's being used" });
this.createSettingsBlock(containerEl, innDescText, this.plugin.settings.innSettings.desc, "Description's");
containerEl.createEl("h4", { text: "Rumors being used" });
this.createSettingsBlock(containerEl, innRumorText, this.plugin.settings.innSettings.rumors, "Rumors");
// END INN'S / TAVERN SETTINGS //
// DRINK SETTINGS //
containerEl.createEl("h2", { text: "Drink Generator Settings" });
const drinkNounText = "";
const drinkAdjText = "";
containerEl.createEl("h4", { text: "Adjectives being used" });
this.createSettingsBlock(containerEl, drinkAdjText, this.plugin.settings.drinkSettings.adj, "Adjectives");
containerEl.createEl("h4", { text: "Nouns being used" });
this.createSettingsBlock(containerEl, drinkNounText, this.plugin.settings.drinkSettings.nouns, "Nouns");
// LOOT SETTINGS //
containerEl.createEl("h2", { text: "Loot Generator Settings" });
const lootNounText = "";
const lootAdjText = "";
containerEl.createEl("h4", { text: "Adjectives being used" });
this.createSettingsBlock(containerEl, lootAdjText, this.plugin.settings.drinkSettings.adj, "Adjectives");
containerEl.createEl("h4", { text: "Nouns being used" });
this.createSettingsBlock(containerEl, lootNounText, this.plugin.settings.drinkSettings.nouns, "Nouns");
// GROUP SETTINGS //
containerEl.createEl("h2", { text: "Group Generator Settings" });
const groupAdjectives =''
const groupNouns = ''
const groupNounsPlural = ''
const groupTypes = ''
const groupSingleDescriptors = ''
containerEl.createEl("h4", { text: "Adjectives being used" });
this.createSettingsBlock(containerEl, groupAdjectives, this.plugin.settings.groupSettings.adj, "Adjectives");
containerEl.createEl("h4", { text: "Nouns being used" });
this.createSettingsBlock(containerEl, groupNouns, this.plugin.settings.groupSettings.nouns, "Nouns");
containerEl.createEl("h4", { text: "Plural Nouns being used" });
this.createSettingsBlock(containerEl, groupNounsPlural, this.plugin.settings.groupSettings.nounsP, "Plural Nouns");
containerEl.createEl("h4", { text: "Group Types being used" });
this.createSettingsBlock(containerEl, groupTypes, this.plugin.settings.groupSettings.groupTypes, "Types");
containerEl.createEl("h4", { text: "Single Descriptors being used" });
this.createSettingsBlock(containerEl, groupSingleDescriptors, this.plugin.settings.groupSettings.singleDescriptors, "Descriptors");
}
}

View file

@ -1,11 +1,9 @@
{
"id": "obsidian-fantasy-content-generator",
"id": "fantasy-content-generator",
"name": "Fantasy Content Generator",
"version": "1.0.1",
"version": "1.2.4",
"minAppVersion": "0.15.0",
"description": "A Fantasy Content Generator for Obsidian",
"author": "Obsidian",
"authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing",
"description": "A Fantasy Content Generator for Obsidian for All Your TTRPG / World Building Needs",
"author": "Gregory Jagermeister ",
"isDesktopOnly": false
}
}

348
modal.ts
View file

@ -1,348 +0,0 @@
import { App, DropdownComponent, Modal, Setting } from "obsidian";
import { nameByRace } from "fantasy-name-generator";
import { familyNameList } from "lists/humanFamilyNames";
import { generateShipName } from "generators/ship";
import { generatorReligions } from "generators/religions";
import { generatorAirships } from "generators/airship";
import { generatorDrinks } from "generators/drink";
import { generatorGroups } from "generators/groups";
import { generatorAnimal_groups } from "generators/animalGroups";
import { generatorMetals } from "generators/metal";
import { generatorMagical_trees } from "generators/magicalTrees";
import { elfFamilyNames } from "lists/elvenFamilyNames";
import { dwarfFamilyNames } from "lists/dwarvenFamilyNames";
import * as FCG from "fantasy-content-generator";
import { generateCityName } from "generators/city";
import { generateLoot } from "generators/loot";
import MyPlugin, { innGeneratorSettings, lootTables } from "main";
import { generateInn } from "generators/inn";
import { generatePathfinderName } from "generators/Pathfinder/pathfinderName";
import { ISettlementDomainObject } from "fantasy-content-generator/dist/interfaces";
import { generateMiscellaneousArtifacts } from "generators/artifact";
const races: string[] = ["none","none", "inn", "settlement", "none", "airships", "drinks","artifacts", "loot", "metals", "magicaltrees", "ship", "none", "animalgroups", "groups", "religion", "none", "aasimars", "catfolk", "fetchlings","halfelf","halforc","hobgoblin","ifrits","kobalds","oreads","ratfolk","sylphs","tengu","tians","tiefling","undines","angel", "cavePerson", "darkelf", "demon", "dragon", "drow", "dwarf", "elf", "fairy", "gnome", "goblin", "halfdemon", "halfling", "highelf", "highfairy", "human", "ogre", "orc"];
const racesDisplayName: string[] = ["Select a Generator to Start","--[Settlements and Buildings]--", "Inn's & Taverns", "Settlement", "--[Objects and Vehicles]--", "Airships", "Drinks","Artifacts", "Loot And Treasure", "Metals", "Magical Trees", "Ship", "--[Groups and Religions]--", "Animal Groups", "Groups", "Religion", "--[Races]--", "Aasimars", "Catfolk", "Fetchlings","Half-Elf","Half-Orc","Hobgoblin","Ifrits","Kobalds","Oreads","Ratfolk","Sylphs","Tengu","Tians","Tiefling","Undines","Angel", "Cave Person", "Dark Elf", "Demon", "Dragon", "Drow", "Dwarf", "Elf", "Fairy", "Gnome", "Goblin", "Half Demon", "Halfling", "High Elf", "High Fairy", "Human", "Ogre", "Orc"];
const pathfinderFilter = ["aasimars", "catfolk", "fetchlings","halfelf","halforc","hobgoblin","ifrits","kobalds","oreads","ratfolk","sylphs","tengu","tians","tiefling","undines"];
let genSettings = {
race: "angel",
gender: "male",
multiNames: false
}
export class GeneratorModal extends Modal {
result: string;
onSubmit: (result: string) => void;
plugin: MyPlugin;
constructor(app: App, onSubmit: (result: string) => void, plugin: MyPlugin) {
super(app);
this.onSubmit = onSubmit;
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
const amountToGen = 1;
contentEl.createEl("h1", { text: "Lets Generate!" });
contentEl.createEl("p", { text: "Welcome to the Fantasy Content Generator! Select the Generator for the name you would like to generate below and then fill out the form." });
contentEl.createEl("h2", { text: "Select the Generator." });
const select = new DropdownComponent(contentEl);
races.forEach((race,index) => {
select.addOption(race, racesDisplayName[index]);
})
const optionsDiv = contentEl.createDiv();
select.onChange((raceSelected) => {
switch (raceSelected) {
default:
this.generatorRaceSettings(optionsDiv, amountToGen, raceSelected);
break;
case "ship":
this.generatorCustomSettings(optionsDiv, amountToGen, generateShipName);
break;
case "religion":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorReligions);
break;
case "inn":
this.generatorInnSettings(optionsDiv, amountToGen, generateInn);
break;
case "airships":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorAirships);
break;
case "drinks":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorDrinks, this.plugin.settings.drinkSettings);
break;
case "groups":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorGroups, this.plugin.settings.groupSettings);
break;
case "animalgroups":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorAnimal_groups);
break;
case "metals":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorMetals);
break;
case "magicaltrees":
this.generatorCustomSettings(optionsDiv, amountToGen, generatorMagical_trees);
break;
case "settlement":
this.generatorFCGSettlementSettings(optionsDiv, amountToGen, FCG.Settlements.generate);
break;
case "loot":
this.generatorLootSettings(optionsDiv, amountToGen, generateLoot, this.plugin.settings.enableCurrency, this.plugin.settings.currencyFrequency, this.plugin.settings.currencyTypes);
break;
case "artifacts":
this.generatorCustomSettings(optionsDiv, amountToGen, generateMiscellaneousArtifacts);
break;
case "none":
optionsDiv.innerHTML = "";
break;
}
});
}
generatorRaceSettings(settingsdiv: HTMLElement, genAmount: number, raceSelected: string) {
genSettings = {
race: "angel",
gender: "male",
multiNames: false
}
genSettings.race = raceSelected;
settingsdiv.innerHTML = "";
settingsdiv.createEl("h3", { text: "Customise The Generation" });
new Setting(settingsdiv)
.setName("Male or Female?")
.addDropdown((drop) => {
drop.addOption("male", "Male");
drop.addOption("female", "Female");
drop.onChange((value) => {
genSettings.gender = value;
})
});
new Setting(settingsdiv)
.setName("Family Name?")
.addToggle((toggle) => {
toggle.onChange((value) => {
genSettings.multiNames = value;
})
})
new Setting(settingsdiv)
.setName("Amount")
.setDesc("How Many Records to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn.setButtonText("Generate")
.setCta()
.onClick(()=>{
for (let index = 0; index < genAmount; index++) {
let firstName;
let familyName = '';
let fullName = '';
if (pathfinderFilter.includes(genSettings.race)) {
fullName = generatePathfinderName(genSettings.race, genSettings.gender, genSettings.multiNames);
} else {
type gender = 'male' | 'female' | undefined;
firstName = nameByRace(genSettings.race, { gender: genSettings.gender as gender});
if (genSettings.multiNames === true) {
familyName = genSettings.race.includes("human") || genSettings.race.includes("dwarf") || genSettings.race.includes("elf") ? " " + this.determineLastname(genSettings.race) : " " + nameByRace(genSettings.race, { gender: genSettings.gender as gender});
}
fullName = firstName + familyName;
}
new Setting(settingsdiv)
.addButton((btn) =>
btn
.setButtonText("Copy")
.setCta()
.onClick(() => {
this.result = fullName;
this.close();
this.onSubmit(this.result);
})).setName(fullName);
}
}))
}
generatorInnSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: (settings: innGeneratorSettings) => {name:string,description:string,rumors:string[]}) {
settingsdiv.innerHTML = "";
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate Names")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
const innName = generatorFunction(this.plugin.settings.innSettings);
console.log(innName);
new Setting(settingsdiv)
.addButton((btn) => {
btn.setButtonText("Copy to Clipboard")
.setCta()
.onClick(() => {
this.result = `Name: ${innName.name}\nDescription: ${innName.description}\nRumors: ${innName.rumors.toString()}`;
this.close()
this.onSubmit(this.result);
})
}).setName(innName.name);
}
}));
}
generatorLootSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: (enableCurrency:boolean, currencyFrequency: number, currencyTypes: object[], lootTable: lootTables) => string, enableCurrency:boolean, currencyFrequency: number, currencyTypes: object[]) {
settingsdiv.innerHTML = "";
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate Names")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
const shipName = generatorFunction(enableCurrency, currencyFrequency, currencyTypes, this.plugin.settings.lootSettings);
new Setting(settingsdiv)
.addButton((btn) => {
btn.setButtonText("Copy to Clipboard")
.setCta()
.onClick(() => {
this.result = shipName;
this.close()
this.onSubmit(this.result);
})
}).setName(shipName);
}
}));
}
generatorFCGSettlementSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: () => ISettlementDomainObject) {
settingsdiv.innerHTML = "";
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate Names")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
const shipName = generatorFunction();
console.log(shipName);
const name = generateCityName(this.plugin.settings.citySettings);
new Setting(settingsdiv)
.addButton((btn) => {
btn.setButtonText("Copy to Clipboard")
.setCta()
.onClick(() => {
this.result = "Name: " + name + "\nPopulation: " + shipName.population +"\nType: "+ shipName.type;
this.close()
this.onSubmit(this.result);
})
}).setName(name + ", Population: " + shipName.population);
}
}));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
generatorCustomSettings(settingsdiv: HTMLElement, genAmount: number, generatorFunction: (settings ?: any) => string, settings ?: any) {
settingsdiv.innerHTML = "";
settingsdiv.createEl("h3", { text: "Customise The Generation" });
genAmount = 1;
new Setting(settingsdiv)
.setName("Amount to Generate")
.addText((text) => {
text.onChange((value) => genAmount = Number(value));
})
.addButton((btn) =>
btn
.setButtonText("Generate Names")
.setCta()
.onClick(() => {
for (let index = 0; index < genAmount; index++) {
let shipName = '';
if (settings !== undefined) {
shipName = generatorFunction(settings);
} else {
shipName = generatorFunction();
}
new Setting(settingsdiv)
.addButton((btn) => {
btn.setButtonText("Copy to Clipboard")
.setCta()
.onClick(() => {
this.result = shipName;
this.close()
this.onSubmit(this.result);
})
}).setName(shipName);
}
}));
}
determineLastname(race: string) {
if (race.includes("human")) {
return this.randomItemFromArray(familyNameList);
}
if (race.includes("elf")) {
return this.randomItemFromArray(elfFamilyNames);
}
if (race.includes("dwarf")) {
return this.randomItemFromArray(dwarfFamilyNames);
}
return "The Unknown"
}
randomItemFromArray(array:string[]) {
const randomIndex = Math.floor(Math.random() * array.length);
return array[randomIndex];
}
onClose() {
const { contentEl } = this;
genSettings = {
race: "angel",
gender: "male",
multiNames: false
}
contentEl.empty();
}
}

2316
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,11 +1,11 @@
{
"name": "fantasy-content-generator",
"version": "1.0.1-a",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
"version": "1.2.4",
"description": "A Fantasy Content Generator For all your TTRPG Needs",
"main": "main.js",
"scripts": {
"dev": "node esbuild.config.mjs",
"build": "tsc -noEmit -skipLibCheck && node esbuild.config.mjs production",
"build": "tsc -noEmit -skipLibCheck && node prod.esbuild.config.mjs production && copy manifest.json fantasy-content-generator && copy styles.css fantasy-content-generator && zip-build fantasy-content-generator builds",
"version": "node version-bump.mjs && git add manifest.json versions.json"
},
"keywords": [],
@ -21,9 +21,15 @@
"esbuild": "0.17.3",
"obsidian": "latest",
"tslib": "2.4.0",
"typescript": "4.7.4"
"typescript": "4.7.4",
"zip-build": "^1.8.0"
},
"dependencies": {
"@codemirror/autocomplete": "^6.4.1",
"@codemirror/commands": "^6.2.1",
"@codemirror/lang-markdown": "^6.0.5",
"@codemirror/lint": "^6.1.1",
"@codemirror/stream-parser": "^0.19.9",
"fantasy-content-generator": "^4.9.1",
"fantasy-name-generator": "^2.0.0",
"react": "^18.2.0",

49
prod.esbuild.config.mjs Normal file
View file

@ -0,0 +1,49 @@
import esbuild from "esbuild";
import process from "process";
import builtins from "builtin-modules";
const banner =
`/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
`;
const prod = (process.argv[2] === "production");
const context = await esbuild.context({
banner: {
js: banner,
},
entryPoints: ["main.ts"],
bundle: true,
external: [
"obsidian",
"electron",
"@codemirror/autocomplete",
"@codemirror/collab",
"@codemirror/commands",
"@codemirror/language",
"@codemirror/lint",
"@codemirror/search",
"@codemirror/state",
"@codemirror/view",
"@lezer/common",
"@lezer/highlight",
"@lezer/lr",
...builtins,
],
format: "cjs",
target: "es2018",
logLevel: "info",
sourcemap: prod ? false : "inline",
treeShaking: true,
outfile: "fantasy-content-generator/main.js",
});
if (prod) {
await context.rebuild();
process.exit(0);
} else {
await context.watch();
}

230
settings/Datatypes.ts Normal file
View file

@ -0,0 +1,230 @@
import * as fs from 'fs';
import { Notice } from 'obsidian';
// The possible Options that could be selected durring inline generation
export const possibleOptions = [
'TradingPost',
'ElfMale',
'ElfMaleLastname',
'ElfFemale',
'ElfFemaleLastname',
'Orc',
'OrcLastname',
'DwarfMale',
'DwarfMaleLastname',
'DwarfFemale',
'DwarfFemaleLastname',
'HumanMale',
'HumanFemale',
'HumanMaleLastname',
'HumanFemaleLastname',
"DungeonsLabryinths",
"InnsTaverns",
"Settlement",
"Airships",
"Drinks",
"Artifacts",
"LootTreasure",
"Metals",
"MagicalTrees",
"Ship",
"AnimalGroups",
"Groups",
"Religion",
"AasimarsLastname",
"CatfolkLastname",
"FetchlingsLastname",
"HalfElfLastname",
"HalfOrcLastname",
"HobgoblinLastname",
"IfritsLastname",
"KobaldsLastname",
"OreadsLastname",
"RatfolkLastname",
"SylphsLastname",
"TenguLastname",
"TiansLastname",
"TieflingLastname",
"UndinesLastname",
"AngelMaleLastname",
"AngelFemaleLastname",
"CavePersonMaleLastname",
"CavePersonFemaleLastname",
"DarkElfMaleLastname",
"DarkElfFemaleLastname",
"DemonLastname",
"DragonMaleLastname",
"DragonFemaleLastname",
"DrowMaleLastname",
"DrowFemaleLastname",
"FairyMaleLastname",
"FairyFemaleLastname",
"GnomeMaleLastname",
"GnomeFemaleLastname",
"GoblinLastname",
"HalfDemonMaleLastname",
"HalfDemonFemaleLastname",
"HalflingMaleLastname",
"HalflingFemaleLastname",
"HighElfMaleLastname",
"HighElfFemaleLastname",
"HighFairyMaleLastname",
"HighFairyFemaleLastname",
"OgreLastname",
"Aasimars",
"Catfolk",
"Fetchlings",
"HalfElf",
"HalfOrc",
"Hobgoblin",
"Ifrits",
"Kobalds",
"Oreads",
"Ratfolk",
"Sylphs",
"Tengu",
"Tians",
"Tiefling",
"Undines",
"AngelMale",
"CavePersonMale",
"DarkElfMale",
"DragonMale",
"DrowMale",
"FairyMale",
"GnomeMale",
"HalfDemonMale",
"HalflingMale",
"HighElfMale",
"HighFairyMale",
"Ogre",
"AngelFemale",
"CavePersonFemale",
"DarkElfFemale",
"Demon",
"DragonFemale",
"DrowFemale",
"FairyFemale",
"GnomeFemale",
"Goblin",
"HalfDemonFemale",
"HalflingFemale",
"HighElfFemale",
"HighFairyFemale",
"PlotStoryHooks"
];
// currency Datatype for defining custom currency
export type currency = {
name: string,
rarity: string
}
// Datatype for collecting group settings
export type groupGenSettings = {
adj: string[],
nouns: string[],
nounsP: string[],
groupTypes: string[],
singleDescriptors: string[]
}
// Datatype for collecting dungeon settings
export type dungeonGenSettings = {
dungeonTypes: string[],
adjectives: string[],
nouns: string[],
locations: string[],
randomDesc: string[]
}
// Datatype for collecting loot settings
export type lootTables = {
adj: string[]
items: { item: string, weight: number }[];
}
// Datatype for collecting Drink settings
export type drinkGeneratorSettings = {
adj: string[],
nouns: string[],
}
// Datatype for collecting city settings
export type cityGeneratorSetting = {
prefixArray: string[],
suffixArray: string[]
}
// Datatype for collecting inn and tavern settings
export type innGeneratorSettings = {
prefixes: string[],
innType: string[],
nouns: string[],
desc: string[],
rumors: string[]
}
export interface FileWithPath extends File {
path: string
}
// the interface that uses all
export interface FantasyPluginSettings {
enableCurrency: boolean;
citySettings: cityGeneratorSetting;
currencyTypes: currency[];
currencyFrequency: number;
innSettings: innGeneratorSettings;
drinkSettings: drinkGeneratorSettings;
lootSettings: lootTables;
groupSettings: groupGenSettings;
dungeonSettings: dungeonGenSettings;
inlineCallout: string;
}
export function importJSON(path: string, callback: (data: object) => void): void {
fs.readFile(path, 'utf8', (error, data) => {
if (error) {
new Notice("Error Importing: " + error);
return;
}
const jsonData = JSON.parse(data);
new Notice("Data Successfully Imported!");
callback(jsonData);
});
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function exportJSON(data: any) {
const json = JSON.stringify(data);
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.download = 'data.json';
a.href = url;
a.click();
new Notice("Data Exporting!");
}
export function weightedRandomItem(table: { string: string, range: number[] }[], roll: number) {
// Find the object in the table that corresponds to the roll
const item = table.find(({ range }) => range[0] <= roll && roll <= range[1]);
// Return the item
return item?.string;
}
export function rollD20(modifier: number) {
return Math.clamp(Math.floor((Math.random() * 20) + 1) + modifier, 1, 20);
}
export function rollD100(modifier: number) {
return Math.clamp(Math.floor((Math.random() * 100) + 1) + modifier, 1, 100);
}

210
settings/DefaultSetting.ts Normal file

File diff suppressed because one or more lines are too long

561
settings/SettingsTab.ts Normal file
View file

@ -0,0 +1,561 @@
import FantasyPlugin from "main";
import { PluginSettingTab, App, Setting, Platform } from "obsidian";
import { cityGeneratorSetting, currency, drinkGeneratorSettings, dungeonGenSettings, exportJSON, FileWithPath, groupGenSettings, importJSON, innGeneratorSettings, lootTables } from "./Datatypes";
import { DEFAULT_SETTINGS } from "./DefaultSetting";
export class SettingTab extends PluginSettingTab {
plugin: FantasyPlugin;
constructor(app: App, plugin: FantasyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
convertStringToArray(string: string, arr: string[]): void {
//const newString = string.replace(/\s/g, '');
const array = string.split(',');
array.forEach((el) => {
arr.push(el);
})
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
createSettingsBlock(containerEl: HTMLElement, textA: string, arr: any[], type: string, weights: boolean): void {
new Setting(containerEl).setName(type + " being used").setDesc("Click 'remove' for any item you want removed from the Array");
new Setting(containerEl)
.setName("New Addition:")
.addTextArea((text) => {
text.onChange((value) => {
textA = value;
})
})
.addButton((btn) => {
btn.setCta().setButtonText("Add")
.onClick(async () => {
this.convertStringToArray(textA, arr);
this.display();
await this.plugin.saveSettings();
})
})
const foldDiv = containerEl.createEl('details', { cls: "OFCGDetails" });
foldDiv.createEl("summary", { text: type, cls: "OFCGSummary" });
for (let index = 0; index < arr.length; index++) {
new Setting(foldDiv)
.setName(weights ? JSON.stringify(arr[index]) : arr[index])
.addButton((btn) => btn
.setCta()
.setButtonText("Remove")
.onClick(async () => {
arr.splice(index, 1);
this.display();
await this.plugin.saveSettings();
})
)
}
containerEl.createEl('hr');
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h1', { text: 'Fantasy Content Generator' });
const generalSettings = containerEl.createDiv("general")
new Setting(generalSettings)
.setName('Reset To Defaults')
.setDesc('Click if you would like to use the default settings again')
.addButton((btn) => {
btn.setCta()
.setButtonText("Reset")
.onClick(async () => {
this.plugin.settings = DEFAULT_SETTINGS;
this.display();
await this.plugin.saveSettings();
})
})
new Setting(generalSettings).setName("Inline Generator Callout").setDesc("Set callout character to activate the inline Generator.")
.addText((text) => {
text.setValue(String(this.plugin.settings.inlineCallout));
text.onChange(async (value) => {
this.plugin.settings.inlineCallout = value;
await this.plugin.saveSettings();
})
})
// CURRENCEY SETTINGS //
const currencyEl = containerEl.createDiv("currencyDiv");
new Setting(currencyEl).setHeading().setName("Currency Settings");
new Setting(currencyEl)
.setName('Enable Currency for Loot Generation.')
.setDesc('If you have Currency in your World or game consider Activating this')
.addToggle((toggle) => {
toggle.setValue(this.plugin.settings.enableCurrency);
toggle.onChange(async (value) => {
this.plugin.settings.enableCurrency = value;
this.display();
await this.plugin.saveSettings();
})
})
if (this.plugin.settings.enableCurrency) {
new Setting(currencyEl).setName("Occurance Rate:").setDesc("Set How Frequently Loot generates currency as a percentage of 100")
.addText((text) => {
text.setValue(String(this.plugin.settings.currencyFrequency));
text.onChange(async (value) => {
if (!(isNaN(+value))) {
this.plugin.settings.currencyFrequency = Number(value);
await this.plugin.saveSettings();
}
})
})
if (Platform.isDesktopApp) {
const importExportFile = new Setting(currencyEl)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "currency",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.currencyTypes = data as currency[];
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.currencyTypes);
})
});
}
const ctext = {
name: '',
rarity: 'common'
}
new Setting(currencyEl)
.setName("Currency Name:")
.addText((text) => {
text.onChange((value) => {
ctext.name = value;
})
}).addDropdown((drop) => {
drop.addOption("common", "Common");
drop.addOption("uncommon", "Uncommon");
drop.addOption("rare", "Rare");
drop.addOption("rarest", "Rarest");
drop.onChange((value) => {
ctext.rarity = value;
})
})
.addButton((btn) => {
btn.setCta().setButtonText("Add")
.onClick(async () => {
this.plugin.settings.currencyTypes.push(ctext);
this.display();
await this.plugin.saveSettings();
})
})
new Setting(currencyEl).setName("Added currency").setDesc("Click Remove on a Currency you would like to Remove");
const foldDiv = currencyEl.createEl('details', { cls: "OFCGDetails" });
foldDiv.createEl("summary", { text: "Currency", cls: "OFCGSummary" });
for (let index = 0; index < this.plugin.settings.currencyTypes.length; index++) {
new Setting(foldDiv)
.setName(this.plugin.settings.currencyTypes[index].name)
.addButton((btn) => btn
.setCta()
.setButtonText("Remove")
.onClick(async () => {
this.plugin.settings.currencyTypes.splice(index, 1);
this.display();
await this.plugin.saveSettings();
})
)
}
}
// END CURRENCY SETTINGS //
currencyEl.createEl('hr');
//SETTLEMENT SETTINGS//
const settlementDiv = containerEl.createDiv("settlementDiv");
new Setting(settlementDiv).setHeading().setName("Settlement Settings");
settlementDiv.createEl('br');
if (Platform.isDesktopApp) {
const importExportFile = new Setting(settlementDiv)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "settlement",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.citySettings = data as cityGeneratorSetting;
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.citySettings);
})
});
}
const preText = "";
const sufText = "";
this.createSettingsBlock(settlementDiv, preText, this.plugin.settings.citySettings.prefixArray, "Prefixes", false);
this.createSettingsBlock(settlementDiv, sufText, this.plugin.settings.citySettings.suffixArray, "Suffixes", false);
// END SETTLEMENT SETTINGS //
// INN'S / TAVERN SETTINGS //
const innDiv = containerEl.createDiv("innDiv");
new Setting(innDiv).setHeading().setName("Inn Settings");
innDiv.createEl('br');
if (Platform.isDesktopApp) {
const importExportFile = new Setting(innDiv)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "inn",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.innSettings = data as innGeneratorSettings;
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.innSettings);
})
});
}
const innPreText = "";
const innTypeText = "";
const innNounText = "";
const innDescText = "";
const innRumorText = "";
this.createSettingsBlock(innDiv, innPreText, this.plugin.settings.innSettings.prefixes, "Prefixes", false);
this.createSettingsBlock(innDiv, innTypeText, this.plugin.settings.innSettings.innType, "Type's", false);
this.createSettingsBlock(innDiv, innNounText, this.plugin.settings.innSettings.nouns, "Nouns", false);
this.createSettingsBlock(innDiv, innDescText, this.plugin.settings.innSettings.desc, "Description's", false);
this.createSettingsBlock(innDiv, innRumorText, this.plugin.settings.innSettings.rumors, "Rumors", false);
// END INN'S / TAVERN SETTINGS //
// DRINK SETTINGS //
const drinkDiv = containerEl.createDiv("drinkDiv");
new Setting(drinkDiv).setHeading().setName("Drink Settings");
drinkDiv.createEl('br');
if (Platform.isDesktopApp) {
const importExportFile = new Setting(drinkDiv)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "drink",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.drinkSettings = data as drinkGeneratorSettings;
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.drinkSettings);
})
});
}
const drinkNounText = "";
const drinkAdjText = "";
this.createSettingsBlock(drinkDiv, drinkAdjText, this.plugin.settings.drinkSettings.adj, "Adjectives", false);
this.createSettingsBlock(drinkDiv, drinkNounText, this.plugin.settings.drinkSettings.nouns, "Nouns", false);
// LOOT SETTINGS //
const lootDiv = containerEl.createDiv("lootDiv");
new Setting(lootDiv).setHeading().setName("Loot Settings");
lootDiv.createEl('br');
if (Platform.isDesktopApp) {
const importExportFile = new Setting(lootDiv)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "loot",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.lootSettings = data as lootTables;
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.lootSettings);
})
});
}
const lootNounText = "";
const lootAdjText = "";
this.createSettingsBlock(lootDiv, lootAdjText, this.plugin.settings.lootSettings.adj, "Adjectives", false);
this.createSettingsBlock(lootDiv, lootNounText, this.plugin.settings.lootSettings.items, "Items", true);
// GROUP SETTINGS //
const groupDiv = containerEl.createDiv("groupDiv");
new Setting(groupDiv).setHeading().setName("Group Settings");
groupDiv.createEl('br');
if (Platform.isDesktopApp) {
const importExportFile = new Setting(groupDiv)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "group",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.groupSettings = data as groupGenSettings;
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.groupSettings);
})
});
}
const groupAdjectives = ''
const groupNouns = ''
const groupNounsPlural = ''
const groupTypes = ''
const groupSingleDescriptors = ''
this.createSettingsBlock(groupDiv, groupAdjectives, this.plugin.settings.groupSettings.adj, "Adjectives", false);
this.createSettingsBlock(groupDiv, groupNouns, this.plugin.settings.groupSettings.nouns, "Nouns", false);
this.createSettingsBlock(groupDiv, groupNounsPlural, this.plugin.settings.groupSettings.nounsP, "Plural Nouns", false);
this.createSettingsBlock(groupDiv, groupTypes, this.plugin.settings.groupSettings.groupTypes, "Types", false);
this.createSettingsBlock(groupDiv, groupSingleDescriptors, this.plugin.settings.groupSettings.singleDescriptors, "Descriptors", false);
// END GROUP SETTINGS //
const dungDiv = containerEl.createDiv("dungDiv");
new Setting(dungDiv).setHeading().setName("Dungeon Settings");
dungDiv.createEl('br');
if (Platform.isDesktopApp) {
const importExportFile = new Setting(dungDiv)
.setName("Import | Export")
.setDesc("Import A Json File With Supported information");
const inputAppfile = createEl("input", {
attr: {
type: "file",
name: "dungeon",
accept: ".json",
multiple: false
}
});
inputAppfile.onchange = async () => {
const { files } = inputAppfile;
if (files === null || !files.length) return;
try {
const file = files[0] as FileWithPath;
importJSON(file.path, async (data) => {
this.plugin.settings.dungeonSettings = data as dungeonGenSettings;
this.display();
await this.plugin.saveSettings();
});
} catch (e) { /* empty */ }
}
importExportFile.addButton((b) => {
b.setButtonText("Choose Import File").setTooltip(
"Import Json File for the Generator"
).buttonEl.appendChild(inputAppfile)
b.buttonEl.addClass("FCGInput");
b.onClick(() => inputAppfile.click());
}).addButton((b) => {
b.setButtonText("Export Section To File").setCta()
.onClick(() => {
exportJSON(this.plugin.settings.dungeonSettings);
})
});
}
const dungAdjectives = ''
const dungNouns = ''
const dungTypes = ''
const dungLocations = ''
const dungRandomDesc = ''
this.createSettingsBlock(dungDiv, dungAdjectives, this.plugin.settings.dungeonSettings.adjectives, "Adjectives", false);
this.createSettingsBlock(dungDiv, dungNouns, this.plugin.settings.groupSettings.nouns, "Nouns", false);
this.createSettingsBlock(dungDiv, dungLocations, this.plugin.settings.dungeonSettings.locations, "Locations", false);
this.createSettingsBlock(dungDiv, dungTypes, this.plugin.settings.dungeonSettings.dungeonTypes, "Types", false);
this.createSettingsBlock(dungDiv, dungRandomDesc, this.plugin.settings.dungeonSettings.randomDesc, "Descriptors", false);
}
}

View file

@ -1,7 +1,20 @@
.OFCGDetails {
border: 1px solid #aaa;
border-radius: 4px;
.theme-light .OFCGDetails {
border: 1px solid #ccc;
box-shadow: 0px 12px 0px 0px rgba(255, 255, 255, 0.37);
background-color: #f0f0f0;
}
.theme-light .OFCGDetails[open] summary {
border-bottom: 1px solid #666;
margin-bottom: 0.5em;
}
.theme-dark .OFCGDetails {
border: 1px solid #272727;
box-shadow: 0px 12px 0px 0px rgba(0, 0, 0, 0.37);
background-color: #313131;
padding: 0.5em 0.5em 0.5em;
margin: 1em;
}
.OFCGSSummary {
@ -14,7 +27,10 @@
padding: 0.5em;
}
.OFCGDetails[open] summary {
.theme-dark .OFCGDetails[open] summary {
border-bottom: 1px solid #aaa;
margin-bottom: 0.5em;
}
.FCGInput>input[type="file"] {
display: none;
}

View file

@ -1,3 +1,5 @@
{
"1.0.1-a": "0.15.0"
}
"1.2.3": "0.15.0",
"1.2.2": "0.15.0",
"1.2.4": "0.15.0"
}