Import coco-letters 0.1.0 upstream source snapshot

Original author: Pierre Sarrazin. Preserve upstream GPLv3-or-later and file-specific notices.
Source: http://sarrazip.com/dev/coco-letters-0.1.0.tar.gz
Archive SHA-256: ad7c7771845e1a35014644fb562634a558abee632e1d7738683db6e9e9e46b94
This commit is contained in:
Brian Holman committed 2026-11-09 23:39:21 -07:00
commit 4cedb2d94a
29 files changed
+20169

No files matched your search

+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
+47
View File
@@ -0,0 +1,47 @@
/* CursorBlinker.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CursorBlinker.h"
void
CursorBlinker_init(CursorBlinker *cb, word *timer)
{
cb->isDisplayed = FALSE;
cb->currentColorIndex = 0xFF; // invalid color index
cb->origColorIndex = 0xFF;
cb->timer = timer;
}
BOOL
CursorBlinker_updateFromTimer(CursorBlinker *cb, byte onColorIndex)
{
cb->newColorIndex = (*cb->timer & 0b11110000) ? onColorIndex : cb->origColorIndex;
return cb->newColorIndex != cb->currentColorIndex;
}
void
CursorBlinker_updateAfterChange(CursorBlinker *cb,
byte colorIndexPreviouslyUnderCursor)
{
if (cb->origColorIndex == 0xFF) // remember the original background color
cb->origColorIndex = colorIndexPreviouslyUnderCursor;
cb->isDisplayed ^= 1;
cb->currentColorIndex = cb->newColorIndex;
}
+53
View File
@@ -0,0 +1,53 @@
/* CursorBlinker.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_CursorBlinker
#define _H_CursorBlinker
#include <coco.h>
typedef struct CursorBlinker
{
BOOL isDisplayed;
byte currentColorIndex;
byte origColorIndex;
byte newColorIndex;
word *timer;
} CursorBlinker;
// timer: Must point to a word that gets incremented every 60th of a second.
// *timer gets overwritten.
// Does not initializer cb->newColorIndex.
//
void CursorBlinker_init(CursorBlinker *cb, word *timer);
// Reads the timer designated to CursorBlinker_init().
// Overwrites cb->newColorIndex.
// Returns TRUE if newColorIndex has been changed by this call.
// In such a case, the caller should draw the cursor in that color.
//
BOOL CursorBlinker_updateFromTimer(CursorBlinker *cb, byte onColorIndex);
void CursorBlinker_updateAfterChange(CursorBlinker *cb,
byte colorIndexPreviouslyUnderCursor);
#endif /* _H_CursorBlinker */
+38
View File
@@ -0,0 +1,38 @@
/* GamePlayer.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GamePlayer.h"
void
GamePlayer_init(GamePlayer *player, BOOL isComputer)
{
player->isComputer = isComputer;
memset(player->rack, TILE_TYPE_NONE, RACK_SIZE); // empty rack
player->score = 0;
}
BOOL
GamePlayer_isRackEmpty(const GamePlayer *player)
{
const byte *p = player->rack;
for (byte i = 0; i < RACK_SIZE; ++i, ++p)
if (*p != TILE_TYPE_NONE)
return FALSE;
return TRUE;
}
+38
View File
@@ -0,0 +1,38 @@
/* GamePlayer.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_GamePlayer
#define _H_GamePlayer
#include "defs.h"
typedef struct GamePlayer
{
BOOL isComputer; // FALSE means user
byte rack[RACK_SIZE]; // array of 1..26, TILE_TYPE_BLANK or TILE_TYPE_NONE
word score;
} GamePlayer;
void GamePlayer_init(GamePlayer *player, BOOL isComputer);
BOOL GamePlayer_isRackEmpty(const GamePlayer *player);
#endif /* _H_GamePlayer */
+597
View File
@@ -0,0 +1,597 @@
/* GameState.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "GameState.h"
#include "dict.h"
// Represents a tile.
//
typedef struct LetterSpec
{
byte numTiles; // number of tiles of this letter
byte numPoints; // points scored when playing this letter
} LetterSpec;
// Tile numbers:
// 0 = blank;
// 1..26 = A..Z.
//
static const LetterSpec letterSpecs[NUM_TILE_TYPES] =
{
{ NUM_BLANK_TILES, 0 },
{ 9, 1 }, // A
{ 2, 3 }, // B
{ 2, 3 }, // C
{ 4, 2 }, // D
{ 12, 1 }, // E
{ 2, 4 }, // F
{ 3, 2 }, // G
{ 2, 4 }, // H
{ 9, 1 }, // I
{ 1, 8 }, // J
{ 1, 5 }, // K
{ 4, 1 }, // L
{ 2, 3 }, // M
{ 6, 1 }, // N
{ 8, 1 }, // O
{ 2, 3 }, // P
{ 1, 10 }, // Q
{ 6, 1 }, // R
{ 4, 1 }, // S
{ 6, 1 }, // T
{ 4, 1 }, // U
{ 2, 4 }, // V
{ 2, 4 }, // W
{ 1, 8 }, // X
{ 2, 4 }, // Y
{ 1, 10 }, // Z
};
#define _ SQ_EMPTY,
#define S SQ_START,
#define T SQ_TRIPLE_WORD,
#define D SQ_DOUBLE_WORD,
#define t SQ_TRIPLE_LETTER,
#define d SQ_DOUBLE_LETTER,
#define EOL }, {
#define EOB }
const byte GameState_boardSquareTypes[BOARD_SIZE][BOARD_SIZE] =
{
{
#include "board.h"
}
};
#undef _
#undef S
#undef T
#undef D
#undef t
#undef d
#undef EOL
#undef EOB
void
GameState_init(GameState *gs)
{
for (byte i = 0; i < NUM_TILE_TYPES; ++i)
gs->numTiles[i] = letterSpecs[i].numTiles;
memset(gs->boardTiles, (char) TILE_TYPE_NONE, BOARD_SIZE * (size_t) BOARD_SIZE);
gs->isBoardEmpty = TRUE;
gs->numPlayedBlankTiles = 0;
}
byte
GameState_getNumTilesOfType(const GameState *gs, byte tileType)
{
if (tileType > 26) // if TILE_TYPE_NONE or invalid
return 0;
return letterSpecs[tileType].numTiles;
}
byte
GameState_getTileValue(const GameState *gs, byte tileType)
{
if (tileType > 26) // if TILE_TYPE_NONE or invalid
return 0;
return letterSpecs[tileType].numPoints;
}
byte
GameState_getBlankTileLetter(const GameState *gs, byte row, byte col)
{
for (byte i = gs->numPlayedBlankTiles; i--; )
{
const PlayedBlankTile *p = &gs->playedBlankTiles[i];
if (p->row == row && p->col == col)
return p->letterTileType;
}
return TILE_TYPE_NONE;
}
void
GameState_setTile(GameState *gs, byte row, byte col,
byte tileType, byte letterTileTypeIfBlank)
{
// If tileType is TILE_TYPE_BLANK, then letterTileTypeIfBlank must be A..Z.
// Otherwise, letterTileTypeIfBlank is not used and should be TILE_TYPE_NONE.
//
assert(tileType != TILE_TYPE_BLANK || letterTileTypeIfBlank >= 1 && letterTileTypeIfBlank <= 26);
assert(tileType == TILE_TYPE_BLANK || letterTileTypeIfBlank == TILE_TYPE_NONE);
gs->boardTiles[row][col] = tileType;
gs->isBoardEmpty = FALSE;
if (tileType == TILE_TYPE_BLANK && gs->numPlayedBlankTiles < NUM_BLANK_TILES)
{
PlayedBlankTile *p = &gs->playedBlankTiles[gs->numPlayedBlankTiles];
p->row = row;
p->col = col;
p->letterTileType = letterTileTypeIfBlank;
++gs->numPlayedBlankTiles;
}
}
byte
GameState_countTilesInBag(const GameState *gs)
{
//printf("GameState_countTilesInBag:");
byte total = 0;
for (byte i = 0; i < NUM_TILE_TYPES; ++i)
{
//printf(" %u=%u", i, gs->numTiles[i]);
total += gs->numTiles[i];
}
//printf("; total=%u\n", total);
return total;
}
byte
GameState_pickRandomLetter(GameState *gs)
{
byte numTiles = GameState_countTilesInBag(gs);
if (numTiles == 0)
return TILE_TYPE_NONE;
byte chosenTileIndex = (byte) (rand() % numTiles); // index among all tiles in bag
//printf("GameState_pickRandomLetter: chosenTileIndex=%u\n", chosenTileIndex);
for (byte i = 0; i < NUM_TILE_TYPES; ++i)
{
byte *numTilesOfTypeI = &gs->numTiles[i];
if (chosenTileIndex < *numTilesOfTypeI)
{
--*numTilesOfTypeI;
//printf("GameState_pickRandomLetter: return %u\n", i);
return i;
}
chosenTileIndex -= *numTilesOfTypeI;
}
return TILE_TYPE_NONE;
}
void
GameState_fillRackEmptySlots(GameState *gs, byte rack[RACK_SIZE])
{
for (byte i = 0; i < RACK_SIZE; ++i)
if (rack[i] == TILE_TYPE_NONE)
rack[i] = GameState_pickRandomLetter(gs);
}
// Returns TRUE if the required free space exists.
//
static BOOL
GameState_checkFreeSpaceLeft(const GameState *gs,
byte row, byte col,
byte numFreeSquaresNeededForNewWord)
{
if (col < numFreeSquaresNeededForNewWord) // not enough columns at left of (row, col)
return FALSE;
for ( ; numFreeSquaresNeededForNewWord > 0; --numFreeSquaresNeededForNewWord)
{
--col;
if (gs->boardTiles[row][col] != TILE_TYPE_NONE)
return FALSE;
}
if (col == 0)
return TRUE;
// One more free space is needed to keep the new word from touching an existing word.
return gs->boardTiles[row][col - 1] == TILE_TYPE_NONE;
}
// Returns TRUE if the required free space exists.
//
static BOOL
GameState_checkFreeSpaceRight(const GameState *gs,
byte row, byte col,
byte numFreeSquaresNeededForNewWord)
{
if (col + numFreeSquaresNeededForNewWord >= BOARD_SIZE) // not enough rows at right of (row, col)
return FALSE;
for ( ; numFreeSquaresNeededForNewWord > 0; --numFreeSquaresNeededForNewWord)
{
++col;
if (gs->boardTiles[row][col] != TILE_TYPE_NONE)
return FALSE;
}
if (col == BOARD_SIZE - 1)
return TRUE;
// One more free space is needed to keep the new word from touching an existing word.
return gs->boardTiles[row][col + 1] == TILE_TYPE_NONE;
}
// Returns TRUE if the required free space exists.
//
static BOOL
GameState_checkFreeSpaceUp(const GameState *gs,
byte row, byte col,
byte numFreeSquaresNeededForNewWord)
{
if (row < numFreeSquaresNeededForNewWord) // not enough rows above (row, col)
return FALSE;
for ( ; numFreeSquaresNeededForNewWord > 0; --numFreeSquaresNeededForNewWord)
{
--row;
if (gs->boardTiles[row][col] != TILE_TYPE_NONE)
return FALSE;
}
if (row == 0)
return TRUE;
// One more free space is needed to keep the new word from touching an existing word.
return gs->boardTiles[row - 1][col] == TILE_TYPE_NONE;
}
// Returns TRUE if the required free space exists.
//
static BOOL
GameState_checkFreeSpaceDown(const GameState *gs,
byte row, byte col,
byte numFreeSquaresNeededForNewWord)
{
if (row + numFreeSquaresNeededForNewWord >= BOARD_SIZE) // not enough rows below (row, col)
return FALSE;
for ( ; numFreeSquaresNeededForNewWord > 0; --numFreeSquaresNeededForNewWord)
{
++row;
if (gs->boardTiles[row][col] != TILE_TYPE_NONE)
return FALSE;
}
if (row == BOARD_SIZE - 1)
return TRUE;
// One more free space is needed to keep the new word from touching an existing word.
return gs->boardTiles[row + 1][col] == TILE_TYPE_NONE;
}
byte
GameState_detectHorizontalPrefix(const GameState *gs, byte row, byte col)
{
if (row >= BOARD_SIZE || col >= BOARD_SIZE)
return 0; // out of bounds
byte before;
for (before = 1; before <= col; ++before)
if (gs->boardTiles[row][col - before] == TILE_TYPE_NONE)
break;
return before - 1;
}
byte
GameState_detectHorizontalSuffix(const GameState *gs, byte row, byte col)
{
if (row >= BOARD_SIZE || col >= BOARD_SIZE)
return 0; // out of bounds
byte after;
for (after = 1; col + after < BOARD_SIZE; ++after)
if (gs->boardTiles[row][col + after] == TILE_TYPE_NONE)
break;
return after - 1;
}
byte
GameState_detectHorizontalWordLimits(const GameState *gs,
byte row, byte col,
byte *startCol)
{
byte before = GameState_detectHorizontalPrefix(gs, row, col);
byte after = GameState_detectHorizontalSuffix(gs, row, col);
byte length = after + before + 1;
if (length == 1)
return 0; // no word found
*startCol = col - before;
return length;
}
byte
GameState_detectVerticalPrefix(const GameState *gs, byte row, byte col)
{
if (row >= BOARD_SIZE || col >= BOARD_SIZE)
return 0; // out of bounds
byte before;
for (before = 1; before <= row; ++before)
if (gs->boardTiles[row - before][col] == TILE_TYPE_NONE)
break;
return before - 1;
}
byte
GameState_detectVerticalSuffix(const GameState *gs, byte row, byte col)
{
if (row >= BOARD_SIZE || col >= BOARD_SIZE)
return 0; // out of bounds
byte after;
for (after = 1; row + after < BOARD_SIZE; ++after)
if (gs->boardTiles[row + after][col] == TILE_TYPE_NONE)
break;
return after - 1;
}
byte
GameState_detectVerticalWordLimits(const GameState *gs,
byte row, byte col,
byte *startRow)
{
byte before = GameState_detectVerticalPrefix(gs, row, col);
byte after = GameState_detectVerticalSuffix(gs, row, col);
byte length = after + before + 1;
if (length == 1)
return 0; // no word found
*startRow = row - before;
return length;
}
char
GameState_getTileTypeChar(byte tileType)
{
switch (tileType)
{
case TILE_TYPE_BLANK: return 127; // DEL character rendered as filled rectangle in 4x8 font
case TILE_TYPE_NONE: return ' ';
default: return '@' + (char) tileType; // 'A'..'Z'
}
}
// Fills destWord[] with the word found at position (row, col) and
// going in the direction given by 'horizontally'.
// row, col: Position of the first letter of the word.
// letterInEmptySquare: Tile value that is used if a board position has no tile.
//
static void
GameState_readWordFromBoard(const GameState *gs,
char destWord[MAX_WORD_LEN + 1],
BOOL horizontally,
byte row,
byte col,
byte length,
char letterInEmptySquare)
{
for (byte i = 0; i < length; ++i)
{
byte tileType = gs->boardTiles[row][col];
if (tileType == TILE_TYPE_BLANK)
tileType = GameState_getBlankTileLetter(gs, row, col);
destWord[i] = (tileType == TILE_TYPE_NONE
? letterInEmptySquare
: GameState_getTileTypeChar(tileType));
if (horizontally)
++col;
else
++row;
}
destWord[length] = '\0';
}
// horizontally: Orientation in which the candidate word is positioned.
// hangLetterOffset: Offset in candidateWord[] of the letter that uses a tile
// already on the board. (Example, if candidateWord is "FOOBAR"
// and hangLetterOffset is 3, then we are trying to place "FOO"
// and "AR" around a "B" tile already on the board.
//
BOOL
GameState_checkAdjacentWords(const GameState *gs,
BOOL horizontally,
byte row,
byte col,
byte hangLetterOffset,
const char *candidateWord,
byte candidateWordLength)
{
// (dRow, dCol) is the couple to add to (row, col) to go forward in reading direction.
sbyte dRow = !horizontally;
sbyte dCol = horizontally;
for (byte i = 0; i < candidateWordLength; ++i, row += dRow, col += dCol)
if (i != hangLetterOffset)
{
// Does candidateWord[i] at (row, col) form a word with the letters adjacent to it?
byte detectedRow, detectedCol, detectedLength;
if (!horizontally)
{
detectedLength = GameState_detectHorizontalWordLimits(gs, row, col, &detectedCol);
detectedRow = row;
}
else
{
detectedLength = GameState_detectVerticalWordLimits(gs, row, col, &detectedRow);
detectedCol = col;
}
if (detectedLength > 0)
{
char detectedWord[MAX_WORD_LEN + 1];
GameState_readWordFromBoard(gs, detectedWord, !horizontally,
detectedRow, detectedCol, detectedLength,
candidateWord[i]);
BOOL isInDict = isWordInDictionary(detectedWord);
if (!isInDict)
return FALSE; // reject because adjacent word not in dictionary
}
}
return TRUE;
}
BOOL
GameState_tryHangWord(const GameState *gs,
const char *candidateWord, byte candidateWordLength,
char boardLetterToHangTo,
byte freeSquaresNeededBeforeForNewWord,
byte freeSquaresNeededAfterForNewWord,
BOOL *outHorizontally, byte *outRow, byte *outCol)
{
//printf("TRYHANGWORD: %c %u %u\n",
// boardLetterToHangTo, freeSquaresNeededBeforeForNewWord, freeSquaresNeededAfterForNewWord);
byte tileTypeToHangTo = boardLetterToHangTo - '@'; // 1..26
for (byte row = 0; row < BOARD_SIZE; ++row)
{
for (byte col = 0; col < BOARD_SIZE; ++col)
{
if (gs->boardTiles[row][col] == tileTypeToHangTo)
{
// N.B.: This version always tries the vertical first and always accepts it if it works.
// This is not an optimal strategy.
if (GameState_checkFreeSpaceUp(gs, row, col, freeSquaresNeededBeforeForNewWord)
&& GameState_checkFreeSpaceDown(gs, row, col, freeSquaresNeededAfterForNewWord)
&& GameState_checkAdjacentWords(gs, FALSE,
row - freeSquaresNeededBeforeForNewWord, col,
freeSquaresNeededBeforeForNewWord,
candidateWord, candidateWordLength))
{
//printf("HANG TO %c VERT. AT (%u, %u)\n", boardLetterToHangTo, row, col);
*outHorizontally = FALSE;
*outRow = row - freeSquaresNeededBeforeForNewWord;
*outCol = col;
return TRUE;
}
if (GameState_checkFreeSpaceLeft(gs, row, col, freeSquaresNeededBeforeForNewWord)
&& GameState_checkFreeSpaceRight(gs, row, col, freeSquaresNeededAfterForNewWord)
&& GameState_checkAdjacentWords(gs, TRUE,
row, col - freeSquaresNeededBeforeForNewWord,
freeSquaresNeededBeforeForNewWord,
candidateWord, candidateWordLength))
{
//printf("HANG TO %c HORIZ. AT (%u, %u)\n", boardLetterToHangTo, row, col);
*outHorizontally = TRUE;
*outRow = row;
*outCol = col - freeSquaresNeededBeforeForNewWord;
return TRUE;
}
}
}
}
//printf("FAIL TO HANG TO %c\n", boardLetterToHangTo);
return FALSE;
}
byte
GameState_getTileWithBoundsChecking(const GameState *self, byte row, byte col)
{
if (row >= BOARD_SIZE) // if 255 (-1) or below last row
return TILE_TYPE_NONE;
if (col >= BOARD_SIZE) // if 255 (-1) or at right of last column
return TILE_TYPE_NONE;
return GameState_getTile(self, row, col);
}
BOOL
GameState_detectCrossingWord(const GameState *gs,
byte initRow,
byte initCol,
byte rowInc,
byte colInc,
byte *foundWordRow,
byte *foundWordCol,
byte *indexOfTileToPlace,
byte *foundWordLen)
{
// First go backward to find the start of the word, if any.
// Backward means left if the caller is processing a vertical word,
// or up if it's a horizontal word.
//
*foundWordRow = initRow;
*foundWordCol = initCol;
*foundWordLen = 0;
for (;;)
{
*foundWordRow -= rowInc;
*foundWordCol -= colInc;
if (*foundWordRow >= BOARD_SIZE || *foundWordCol >= BOARD_SIZE)
break; // now to the left of the board, or above it, so stop
if (GameState_getTile(gs, *foundWordRow, *foundWordCol) == TILE_TYPE_NONE)
break; // reached an empty tile, so stop
++*foundWordLen;
}
*indexOfTileToPlace = *foundWordLen;
// Get back to the last non-empty tile seen.
//
*foundWordRow += rowInc;
*foundWordCol += colInc;
// Go forward (i.e., right or down) to find the end of the word, if any.
//
byte wordEndRow = initRow, wordEndCol = initCol;
for (;;)
{
wordEndRow += rowInc;
wordEndCol += colInc;
if (wordEndRow >= BOARD_SIZE || wordEndCol >= BOARD_SIZE)
break; // now to the left of the board, or above it, so stop
if (GameState_getTile(gs, wordEndRow, wordEndCol) == TILE_TYPE_NONE)
break; // reached an empty tile, so stop
++*foundWordLen;
}
// (wordEndRow, wordEndCol) is now one PAST the last letter.
++*foundWordLen; // count the tile to place
//printf("\t""detectCrossingWord: (%u, %u) -> (%u, %u), %u.\n",
// *foundWordRow, *foundWordCol, wordEndRow, wordEndCol, *foundWordLen);
return *foundWordLen > 1;
}
+170
View File
@@ -0,0 +1,170 @@
/* GameState.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_GameState
#define _H_GameState
#include "defs.h"
typedef struct PlayedBlankTile
{
byte row, col; // position where blank tile played on board
byte letterTileType; // 1..26 = A..Z
} PlayedBlankTile;
typedef struct GameState
{
// Bag of tiles from which the players pick at random.
// Indexed with TILE_TYPE_BLANK and 1..26.
//
byte numTiles[NUM_TILE_TYPES];
byte boardTiles[BOARD_SIZE][BOARD_SIZE]; // TILE_TYPE_BLANK, 1..26 = A..Z, TILE_TYPE_NONE
BOOL isBoardEmpty;
byte numPlayedBlankTiles;
PlayedBlankTile playedBlankTiles[NUM_BLANK_TILES]; // only indices < numPlayedBlankTiles are used
} GameState;
// Matrix of SQ_* enum values.
//
extern const byte GameState_boardSquareTypes[BOARD_SIZE][BOARD_SIZE];
void GameState_init(GameState *gs);
byte GameState_getNumTilesOfType(const GameState *gs, byte tileType);
// Returns the number of points associated with the given tile type,
// without regard to where on the board it gets played.
//
byte GameState_getTileValue(const GameState *gs, byte tileType);
// row, col: 0..BOARD_SIZE-1.
// No bounds checking.
// A cast is used to prevent using this function to change the board.
//
#define GameState_getTile(gs, row, col) ((byte) (gs)->boardTiles[row][col])
// Like GameState_getTile() but checks if the coordinates are valid.
// If they are not, returns TILE_TYPE_NONE.
//
byte GameState_getTileWithBoundsChecking(const GameState *self,
byte row, byte col);
// Returns the letter tile type (1..26) represented by the blank at
// the specified position, if any. Otherwise, returns TILE_TYPE_NONE.
//
byte GameState_getBlankTileLetter(const GameState *gs, byte row, byte col);
// Sets square (row, col) to tileType.
// If tileType is TILE_TYPE_BLANK, remembers that the blanks
// represents letterTileTypeIfBlank, which then must be 1..26.
// Must not be used for from than NUM_BLANK_TILES.
// This is ensured by how the bag is initialized using
// NUM_BLANK_TILES by GameState_init().
//
void GameState_setTile(GameState *gs, byte row, byte col,
byte tileType, byte letterTileTypeIfBlank);
#define GameState_isBoardEmpty(gs) ((gs)->isBoardEmpty)
byte GameState_countTilesInBag(const GameState *gs);
// Pick a tile at random from the bag.
// Returns TILE_TYPE_BLANK or 1..26 upon success, TILE_TYPE_NONE upon failure.
//
byte GameState_pickRandomLetter(GameState *gs);
void GameState_fillRackEmptySlots(GameState *gs, byte rack[RACK_SIZE]);
BOOL GameState_tryHangWord(const GameState *gs,
const char *candidateWord, byte candidateWordLength,
char boardLetterToHangTo,
byte freeSquaresNeededBefore,
byte freeSquaresNeededAfter,
BOOL *outHorizontally, byte *outRow, byte *outCol);
BOOL GameState_checkAdjacentWords(const GameState *gs,
BOOL horizontally,
byte row,
byte col,
byte hangLetterOffset,
const char *candidateWord,
byte candidateWordLength);
// tileType: TILE_TYPE_BLANK, 1..26 or TILE_TYPE_NONE.
//
char GameState_getTileTypeChar(byte tileType);
BOOL GameState_detectCrossingWord(const GameState *gs,
byte initRow,
byte initCol,
byte rowInc,
byte colInc,
byte *foundWordRow,
byte *foundWordCol,
byte *indexOfTileToPlace,
byte *foundWordLen);
byte GameState_detectHorizontalPrefix(const GameState *gs, byte row, byte col);
byte GameState_detectHorizontalSuffix(const GameState *gs, byte row, byte col);
byte GameState_detectVerticalPrefix(const GameState *gs, byte row, byte col);
byte GameState_detectVerticalSuffix(const GameState *gs, byte row, byte col);
// Returns the length of the detected word, or zero if none found.
// If the returned length is not zero, *startCol becomes the starting column
// of the detected word.
//
byte GameState_detectHorizontalWordLimits(const GameState *gs,
byte row, byte col,
byte *startCol);
// Returns the length of the detected word, or zero if none found.
// If the returned length is not zero, *startRow becomes the starting row
// of the detected word.
//
byte GameState_detectVerticalWordLimits(const GameState *gs,
byte row, byte col,
byte *startRow);
#endif /* _H_GameState */
+128
View File
@@ -0,0 +1,128 @@
# Memory map after initialization
Banks Address Size Description
0 0000 8 k Dictionary access bank.
1..3 2000 24 k Code and global variables.
4..6 8000 24 k Graphics screen (256x192x16).
7 E000 960 B 32x16 and 40x24 (no attributes) text screens.
7 E3C0 768 B 4x7 font (right side text).
7 E6C0 256 B 5x8 font (used on board).
7 E7C0 5696 B Stack space.
7 FE00 238 B Not used.
- FEEE 18 B CoCo 3 Interrupt vectors.
- FF00 256 B I/O addresses.
## MMU blocks
48..50 Word dictionary.
51..53 Graphics screen.
54..56 Word dictionary.
57..59 Code and global variables.
60..62 Word dictionary.
63 Text screen, fonts, stack space.
# Automating the keyboard
To automate keystrokes, edit the `scriptedKeys[]` array in main.c.
Use `\r` to represent the Enter key.
The `pollKeyboard()` function will return each of the characters
in that array before calling `Keyboard_poll()`.
# Word list
The `word-list.txt` word list is based on `enable.txt` from figshare.com,
with a few edits, and is in the public domain.
See <https://figshare.com/articles/dataset/Enable_Scrabble_Dictionary/7492499>.
Variables `MIN_WORD_LEN` and `MAX_WORD_LEN` in the Makefile determine
which words get selected from that word list.
Variable `MAX_NUM_DICT_BLOCKS` in the Makefile limits the number of
8k blocks that can be used to contain the selected words.
The `dictMMUBlockIndexes[]` array in dict.c must contain that number
of MMU block indexes.
# Data file format
The data file is named by variable `DATA_FILENAME` in the Makefile
and is generated by `build-data.pl` and read by `loadDataFile()`
in dict.c.
The format:
* Sectors that contain the 4x8 font used in the right side of
the game screen. (See `FONT_4x8_BUFFER`, `FONT_4x8_SECTORS`.)
* Sectors that contain the 5x8 font used on the board.
(See `FONT_5x8_BUFFER`, `FONT_5x8_SECTORS`.)
* Sequence of 8k blocks:
* 16-bit big endian unsigned word: Number of words in the 8k block.
* List of words:
* One byte per character of the word.
* Bit 7 of the last byte of the word is 1.
(This prevents support for Latin-1 characters.)
Putting the font data in the data file instead of the executable
allowed shrinking the size of the latter. This was useful to avoid
reaching the limit at $7F80, which is necessary for the LOADM
command to be able to load the entire file.
The fonts are defined by C files because those files define
byte arrays that used to be included in the compilation.
# Text window at the right of the board
At the right of the board is a text window of 14 columns by 24 rows.
`writeStringAt()` is the main function to use to write text.
Calls to `printf()`, `putchar()`, etc. print to a subwindow of
14 columns by 8 rows at the bottom. This subwindow can be used to
print debugging information.
See `TEXT_WIN_LEFT`, `TEXT_WIN_TOP`, `TEXT_WIN_WIDTH`, `TEXT_WIN_HEIGHT`,
etc., in defs.h.
# Tile types
`TILE_TYPE_NONE` represents the absence of any tile on a board square.
`TILE_TYPE_BLANK` represents an unmarked wildcard that can represent
any letter.
Values 1 to 26 represent letters A to Z.
# Tile values in points
These are defined in the letterSpecs[] array in GameState.c.
# Debugging with traces in the Becker port
During the game, printf() et al. print to a small text window at the
buttom right corner of the game screen.
This can be used for debugging, as long as the quantity of traces
is small.
For larger traces, sending the output to a CoCo emulator's Becker port
is more viable.
To do this, edit `graphics.c` and uncomment this line:
//#define TRACES_TO_BECKER_PORT
Then build. Before launching the emulator, a server on the same machine
must be listening to TCP port 65504. This server should then copy all
the traces it receives to standard output or to a file.
This only applies to the graphical screen, not to the help screen.
+205
View File
@@ -0,0 +1,205 @@
PACKAGE = coco-letters
VERSION = 0.1.0
DISPLAY_NAME = CoCo Letters
# Must be at most 8 characters.
PACKAGE_SHORT = letters
# Length of the words to be selected from file $(WORDLIST).
MIN_WORD_LEN = 2
MAX_WORD_LEN = 5
# Maximum number of MMU blocks that can contain dictionary entries.
# See the memory map in HACKING.md.
MAX_NUM_DICT_BLOCKS = 9
# Required libraries.
DECBFILE_LIB = decbfile
DECBFILE_LIB_DIR = decbfile
BCONTROL_LIB = bcontrol
BCONTROL_LIB_DIR = bcontrol
BSOUND_LIB = bsound
BSOUND_LIB_DIR = bsound
# Main program.
SRC = \
main.c \
graphics.c \
file.c \
dict.c \
GameState.c \
GamePlayer.c \
WordSearch.c \
CursorBlinker.c \
PositionIterator.c
# N.B.: font4x8-ascii.c and font5x8-A-Z.c are not compiled.
# They are read by $(BUILD_DATA) to generate part of the game data file.
GENERATED_SRC = $(WORD_LENGTH_FILENAME)
HEADERS = \
defs.h \
graphics.h \
file.h \
dict.h \
GameState.h \
GamePlayer.h \
WordSearch.h \
palette.h \
board.h \
CursorBlinker.h \
PositionIterator.h
LIBS = -L $(DECBFILE_LIB_DIR) -l$(DECBFILE_LIB) \
-L $(BCONTROL_LIB_DIR) -l$(BCONTROL_LIB) \
-L $(BSOUND_LIB_DIR) -l$(BSOUND_LIB)
BIN = $(PACKAGE_SHORT).bin
DSK = $(PACKAGE)-$(VERSION).dsk
PCLEARARG = 1
# Dictionary.
# List of words.
WORDLIST = word-list.txt
# Files generated by the BUILD_DATA script from $(WORDLIST).
DATA_FILENAME = $(PACKAGE_SHORT).dat
WORD_LENGTH_FILENAME = word-length-index.c
# Script that builds DATA_FILENAME.
#
BUILD_DATA = build-data.pl
# Compilation and linking flags.
# The limit is $7F80 because 128 bytes are left for Basic's stack,
# which still exists at the moment when the user EXECs $(BIN).
#
ORG = --org=2000 --limit=7F80
TARGET = coco
INTERMEDIATE = #--intermediate
WERROR = -Werror
STACKSPACE = 2048
OPTIM = -fomit-frame-pointer -Oy
NDEBUG = -DNDEBUG
# Unsigned 16 bit integer other than 0.
# If defined, gets passed to srand().
# If not defined, timer is used.
#
FIXED_SEED = #-DFIXED_SEED=42
DEFINES = \
'-DDISPLAY_NAME="$(DISPLAY_NAME)"' \
-DVERSION=\"$(VERSION)\" \
$(NDEBUG) \
-DDATA_FILENAME=\"$(DATA_FILENAME)\" \
-DMIN_WORD_LEN=$(MIN_WORD_LEN) \
-DMAX_WORD_LEN=$(MAX_WORD_LEN) \
-DMAX_NUM_DICT_BLOCKS=$(MAX_NUM_DICT_BLOCKS) \
$(FIXED_SEED)
CFLAGS = --$(TARGET) $(WERROR) $(INTERMEDIATE) $(NO_RELOCATE) $(OPTIM) \
$(DEFINES) \
-I $(DECBFILE_LIB_DIR) -I $(BCONTROL_LIB_DIR) -I $(BSOUND_LIB_DIR) \
--stack-space=$(STACKSPACE)
LDFLAGS = --$(TARGET) $(ORG) $(INTERMEDIATE)
OBJ = $(GENERATED_SRC:.c=.o) $(SRC:.c=.o)
DISTFILES = \
README.md HACKING.md COPYING \
Makefile \
$(SRC) $(HEADERS) font4x8-ascii.c font5x8-A-Z.c autostart.c \
$(BUILD_DATA) $(WORDLIST)
# Tools.
CMOC = cmoc
PERL = perl
TAR = tar
WRITECOCOFILE = writecocofile
INSTALL_LOADER = install-coco-boot-loader
XROAR = xroar
PARSE_COCO_BIN = parse-coco-bin
all: $(DSK)
$(BIN): $(OBJ) $(DECBFILE_LIB_DIR)/lib$(DECBFILE_LIB).a \
$(BCONTROL_LIB_DIR)/lib$(BCONTROL_LIB).a \
$(BSOUND_LIB_DIR)/lib$(BSOUND_LIB).a
$(CMOC) -o $(BIN) $(LDFLAGS) $(OBJ) $(LIBS)
.PHONY: dict
dict: $(WORD_LENGTH_FILENAME)
$(DATA_FILENAME) $(WORD_LENGTH_FILENAME): $(BUILD_DATA) $(WORDLIST) defs.h
$(PERL) $(BUILD_DATA) $(WORDLIST) $(DATA_FILENAME) $(WORD_LENGTH_FILENAME) $(MIN_WORD_LEN) $(MAX_WORD_LEN) $(MAX_NUM_DICT_BLOCKS)
test -f $(DATA_FILENAME)
test -f $(WORD_LENGTH_FILENAME)
$(DSK): $(BIN) $(DATA_FILENAME) autostart.bin
$(PERL) -e 'print chr(255) x (35*18*256)' > $(DSK)
$(INSTALL_LOADER) $(DSK) autostart.bin
$(WRITECOCOFILE) --allocate-after-dir $(DSK) $(BIN)
$(WRITECOCOFILE) --allocate-before-dir $(DSK) $(DATA_FILENAME)
# Loader that goes on track 34 to be executed by the CoCo DOS command.
autostart.bin: autostart.c Makefile
$(CMOC) --dos -o $@ -D'COMMAND="CLEAR8:PCLEAR$(PCLEARARG):LOADM\"$(PACKAGE_SHORT)\":EXEC"' autostart.c
.PHONY: sizes
sizes: $(BIN)
$(PARSE_COCO_BIN) $(BIN)
%.o: %.c
$(CMOC) -c $(CFLAGS) -o $@ $<
.PHONY: clean-dict
clean-dict:
rm -f $(DATA_FILENAME) $(WORD_LENGTH_FILENAME)
clean: clean-dict
rm -f $(BIN) autostart.bin $(OBJ) $(OBJ:.o=.s) $(OBJ:.o=.lst) $(PACKAGE).map $(PACKAGE).link
distclean: clean
rm -f $(GENERATED_SRC) $(SRC:.c=.d)
.PHONY: dist distcheck
dist:
$(TAR) -czf $(PACKAGE)-$(VERSION).tar.gz --transform 's,^,$(PACKAGE)-$(VERSION)/,' $(DISTFILES)
distcheck: dist
mkdir ,distcheck
$(TAR) -C ,distcheck -xzf $(PACKAGE)-$(VERSION).tar.gz
$(MAKE) -C ,distcheck/$(PACKAGE)-$(VERSION) \
DECBFILE_LIB_DIR=../../$(DECBFILE_LIB_DIR) \
BCONTROL_LIB_DIR=../../$(BCONTROL_LIB_DIR) \
BSOUND_LIB_DIR=../../$(BSOUND_LIB_DIR)
rm -fr ,distcheck
@echo "SUCCESS: $(PACKAGE)-$(VERSION).tar.gz ready for distribution"
.PHONY: binaries
binaries: $(DSK)
$(TAR) -czf $(PACKAGE)-$(VERSION)-binaries.tar.gz $(PACKAGE)-$(VERSION).dsk
# Runs make with arguments $(RECURSION) in the library projects used by this package.
# Supports the -n (dry run) option.
# Example: make recurse RECURSION=clean
#
.PHONY: recurse
recurse:
$(MAKE) -C $(DECBFILE_LIB_DIR) $(RECURSION)
$(MAKE) -C $(BCONTROL_LIB_DIR) $(RECURSION)
$(MAKE) -C $(BSOUND_LIB_DIR) $(RECURSION)
# Automatic prerequisite generation.
%.d: %.c
$(CMOC) --deps-only $(CFLAGS) $<
.PHONY: cleandeps
cleandeps:
rm -f $(SRC:.c=.d)
include $(SRC:.c=.d)
+47
View File
@@ -0,0 +1,47 @@
/* PositionIterator.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "PositionIterator.h"
void
PositionIterator_init(PositionIterator *self, BOOL across, byte *row, byte *col)
{
self->across = across;
self->row = row;
self->col = col;
}
void
PositionIterator_increment(PositionIterator *self)
{
if (self->across)
++*self->col;
else
++*self->row;
}
void
PositionIterator_decrement(PositionIterator *self)
{
if (self->across)
--*self->col;
else
--*self->row;
}
+48
View File
@@ -0,0 +1,48 @@
/* PositionIterator.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_PositionIterator
#define _H_PositionIterator
#include <coco.h>
// Object that decrements a coordinate, but not the other,
// depending on the value of 'across'.
//
typedef struct PositionIterator
{
BOOL across;
byte *row;
byte *col;
} PositionIterator;
void PositionIterator_init(PositionIterator *self, BOOL across, byte *row, byte *col);
// Increments *col if across is TRUE; increments *row otherwise.
//
void PositionIterator_increment(PositionIterator *self);
// Decrements *col if across is TRUE; decrements *row otherwise.
//
void PositionIterator_decrement(PositionIterator *self);
#endif /* _H_PositionIterator */
+36
View File
@@ -0,0 +1,36 @@
# Word Game
Copyright © 2026 Pierre Sarrazin <http://sarrazip.com/>
License: GNU GPL v3 or later, except where stated otherwise.
See file COPYING.
Home page: <http://sarrazip.com/dev/FIXME.html>
Insert the floppy disk that contains this game in drive 0,
then type DOS and press the Enter key.
# Requirements
## Hardware
* CoCo 3.
* RGB monitor.
* Floppy disk controller.
## Software
These libraries are needed to build this game from its source code:
* decbfile (>= 0.1.13)
* bcontrol (>= 0.1.6) (keyboard and joystick support)
* bsound (>= 0.1.4) (sound)
They can be obtained from the CMOC Home Page.
# Version history
0.1.0 20??-FIXME First public release.
+238
View File
@@ -0,0 +1,238 @@
/* WordSearch.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "WordSearch.h"
#include "GameState.h"
#include "PositionIterator.h"
void
WordSearch_init(WordSearch *ws,
byte *rack,
BOOL allInRack,
byte difficultyLevel,
const GameState *gs)
{
ws->rack = rack;
ws->allInRack = allInRack;
ws->difficultyLevel = difficultyLevel;
ws->numWordsProcessed = 0;
ws->foundWord[0] = '\0';
ws->foundWordRow = ws->foundWordCol = 0;
ws->foundWordHorizontal = FALSE;
ws->gameState = gs;
}
void
WordSearch_initWordWalk(const WordSearch *ws,
byte *row,
byte *col,
byte *rowInc,
byte *colInc,
const char **wordToPlace,
byte *wordLen)
{
assert(ws->foundWordRow < BOARD_SIZE);
*row = ws->foundWordRow;
*col = ws->foundWordCol;
if (ws->foundWordHorizontal)
{
*rowInc = 0;
*colInc = 1;
}
else
{
*rowInc = 1;
*colInc = 0;
}
*wordToPlace = ws->foundWord;
*wordLen = (byte) strlen(*wordToPlace);
}
// wordFactor: In/out. May get multiplied by 2 or 3.
//
static void
processSquareType(byte row, byte col,
byte *squareType, byte *wordFactor, byte *letterFactor)
{
*squareType = GameState_boardSquareTypes[row][col];
*letterFactor = 1;
switch (*squareType)
{
case SQ_EMPTY: break;
case SQ_START: *wordFactor *= 2; break;
case SQ_TRIPLE_WORD: *wordFactor *= 3; break;
case SQ_DOUBLE_WORD: *wordFactor *= 2; break;
case SQ_TRIPLE_LETTER: *letterFactor = 3; break;
case SQ_DOUBLE_LETTER: *letterFactor = 2; break;
default: assert(FALSE);
}
}
// wordFactor: In/out.
// tileToPlace: 1..26, or TILE_TYPE_BLANK.
// Returns a number of points scored.
//
static word
countPointsOfTileToPlace(const GameState *gs,
byte tileToPlace,
byte row,
byte col,
byte *wordFactor)
{
byte tileOnBoard = GameState_getTile(gs, row, col);
//printf("\t\t""countPointsOfTileToPlace: row=%u, col=%u: tileOnBoard=%u\n", row, col, tileOnBoard);
if (tileOnBoard != TILE_TYPE_NONE)
return 0; // square already occupied, so no points
byte squareType;
byte letterFactor;
processSquareType(row, col, &squareType, wordFactor, &letterFactor);
//printf("\t\t""countPointsOfTileToPlace: squareType=%u, wordFactor=%u, letterFactor=%u\n",
// squareType, *wordFactor, letterFactor);
// Count the tile's points.
byte tilePoints = GameState_getTileValue(gs, tileToPlace);
//printf("\t\t""countPointsOfTileToPlace: tileToPlace=%u, tilePoints=%u.\n",
// tileToPlace, tilePoints);
return (word) tilePoints * letterFactor;
}
typedef struct CrossingWord
{
BOOL across;
byte row;
byte col;
byte indexOfTileToPlace;
byte tileToPlace;
byte length;
byte blankIndex; // index in the crossing word
} CrossingWord;
static word
countPointsOfCrossingWords(const GameState *gs,
const CrossingWord crossingWords[],
byte numCrossingWords)
{
word wordValue = 0;
byte wordFactor = 1;
for (byte w = 0; w < numCrossingWords; ++w)
{
const CrossingWord *cw = &crossingWords[w];
byte row = cw->row, col = cw->col;
//printf("\t""countPointsOfCrossingWords: w=%u, (%u, %u)\n", w, row, col);
PositionIterator posIter;
PositionIterator_init(&posIter, cw->across, &row, &col);
for (byte i = 0; i < cw->length; ++i)
{
byte tileToPlace;
if (i == cw->blankIndex)
tileToPlace = TILE_TYPE_BLANK;
else if (i == cw->indexOfTileToPlace)
tileToPlace = cw->tileToPlace;
else
tileToPlace = TILE_TYPE_NONE; // tile already on board is worth 0
//printf("\t\t""i=%u, tileToPlace=%u\n", i, tileToPlace);
// This may multiply *wordFactor by 2 or 3.
//
word tilePoints = countPointsOfTileToPlace(
gs, tileToPlace, row, col, &wordFactor);
//printf("\t\t"" tilePoints=%u\n", tilePoints);
wordValue += tilePoints;
PositionIterator_increment(&posIter);
}
}
//printf("\t""countPointsOfCrossingWords: wordValue=%u, wordFactor=%u\n", wordValue, wordFactor);
return wordValue * wordFactor;
}
word
WordSearch_countPointsFromWordsPlayed(const WordSearch *ws, const GameState *gs)
{
byte row, col, rowInc, colInc, wordLen;
const char *wordToPlace;
WordSearch_initWordWalk(ws, &row, &col, &rowInc, &colInc, &wordToPlace, &wordLen);
//printf("countPoints: row=%u, col=%u, rowInc=%u, colInc=%u, wordLen=%u, wordToPlace='%s', wordLen=%u.\n",
// row, col, rowInc, colInc, wordLen, wordToPlace, wordLen);
word wordValue = 0;
byte wordFactor = 1;
CrossingWord foundCrossingWords[MAX_WORD_LEN];
byte numFoundCrossingWords = 0;
for (byte i = 0; i < wordLen; ++i, row += rowInc, col += colInc)
{
byte letterTileTypeBehindBlank = ws->letterTileTypeBehindBlank[i];
byte tileToPlace = (letterTileTypeBehindBlank == TILE_TYPE_NONE ? wordToPlace[i] - '@' : TILE_TYPE_BLANK);
wordValue += countPointsOfTileToPlace(gs, tileToPlace, row, col, &wordFactor);
// Detect if a word crosses the current letter at (row, col).
// Pass colInc and rowInc in reverse order, so that this call
// advances perpendicularly.
//
CrossingWord *cw = &foundCrossingWords[numFoundCrossingWords];
if (numFoundCrossingWords < MAX_WORD_LEN
&& GameState_detectCrossingWord(gs, row, col, colInc, rowInc,
&cw->row, &cw->col,
&cw->indexOfTileToPlace,
&cw->length))
{
cw->tileToPlace = tileToPlace;
cw->across = !ws->foundWordHorizontal;
// If letter at i is a blank, remember the position
// of the blank in the crossing word.
//
cw->blankIndex = (letterTileTypeBehindBlank == TILE_TYPE_NONE ? 0xFF : i);
//printf(" cw->blankIndex=%u\n", cw->blankIndex);
++numFoundCrossingWords;
}
}
wordValue *= wordFactor;
//printf(" %u*%u=%u\n", wordValue, wordFactor, wordValue * wordFactor);
//printf(" numFoundCrossingWords=%u\n", numFoundCrossingWords);
word crossingWordsValue = countPointsOfCrossingWords(
gs, foundCrossingWords, numFoundCrossingWords);
//printf(" crossingWordsValue=%u\n", crossingWordsValue);
return wordValue + crossingWordsValue;
}
+66
View File
@@ -0,0 +1,66 @@
/* WordSearch.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_WordSearch
#define _H_WordSearch
#include <coco.h>
typedef struct WordSearch
{
byte *rack;
BOOL allInRack;
byte difficultyLevel; // LEVEL_* value; only used for computer's search
size_t numWordsProcessed;
char foundWord[MAX_WORD_LEN + 1]; // NUL-terminated string of letters (no blanks)
// If a blank tile was used for foundWord[i], then letterTileTypeBehindBlank[i] is 1..26,
// to indicate which letter the blank represents. Otherwise, it is TILE_TYPE_NONE.
byte letterTileTypeBehindBlank[MAX_WORD_LEN];
byte foundWordRow;
byte foundWordCol;
BOOL foundWordHorizontal;
const struct GameState *gameState;
} WordSearch;
void WordSearch_init(WordSearch *ws,
byte *rack,
BOOL allInRack,
byte difficultyLevel,
const struct GameState *gs);
void WordSearch_initWordWalk(const WordSearch *ws,
byte *row,
byte *col,
byte *rowInc,
byte *colInc,
const char **wordToPlace,
byte *wordLen);
// Must be called before placing the word on the board.
//
word WordSearch_countPointsFromWordsPlayed(const WordSearch *ws,
const struct GameState *gs);
#endif /* _H_WordSearch */
+80
View File
@@ -0,0 +1,80 @@
// autostart.c - Program to be run by the Disk Basic DOS command.
// By Pierre Sarrazin <http://sarrazip.com/>
// This file is in the public domain.
//
// Reference: Roger Schrag, "A Special Use For The DOS Command",
// The Rainbow, November 1984, p.140.
//
// To compile: cmoc --dos autostart.c
// To install on CoCo disk image: install-coco-boot-loader some-image.dsk autostart.bin
// To run on CoCo: type DOS and <Enter> to automatically run *.BAS.
//
// Version history:
// 0.1.0 2016-01-16 Use of legacy.h discontinued.
// 0.1.1 2018-04-03 Adapted to CMOC 0.1.51 (const).
// 0.1.2 2018-08-04 Basic line now forced to be uppercase.
#include <coco.h>
#define ENDFLG 0x00 // STOP/END FLAG: POSITIVE=STOP, NEG=END
#define CINBFL 0x70 // CONSOLE IN BUFFER FLAG: 00=NOT EMPTY, $FF=EMPTY
#define RVEC4 0x016a // RAM hook: CONSOLE IN
byte oldHookInstr;
word oldHookAddr;
const char *basicLineReader;
void feedKeyboard()
{
word preservedX;
asm("stx", preservedX);
* (byte *) CINBFL = 0; // console in buffer now not empty
char nextBasicByte = (char) toupper(*basicLineReader);
++basicLineReader;
if (nextBasicByte == 0) // if finished returning Basic line
{
* (byte *) RVEC4 = oldHookInstr;
* (word *) (RVEC4 + 1) = oldHookAddr;
nextBasicByte = '\r'; // return "Enter" to cause execution of Basic line
}
asm {
lda nextBasicByte
ldx preservedX
tfr u,s // discard stack frame
leas 4,s // discard previous stack frame ptr and return addr
rts // return to caller of CONSOLE IN
}
}
int main()
{
* (byte *) ENDFLG = - * (byte *) ENDFLG; // why?
basicLineReader =
#ifndef COMMAND
"RUN\"*.BAS\""
#else
COMMAND
#endif
;
// Install function feedKeyboard() as CONSOLE IN routine.
//
oldHookInstr = * (byte *) RVEC4;
oldHookAddr = * (word *) (RVEC4 + 1);
* (byte *) RVEC4 = 0x7e; // JMP instruction
* (void **) (RVEC4 + 1) = (void *) feedKeyboard;
* (word *) 0x2600 = 0; // overwrite "OS" marker with two null bytes
asm("jmp", "$ac7c"); // go interpret a Basic line (which is read from console)
return 0; // avoids compiler error
}
+32
View File
@@ -0,0 +1,32 @@
/* board.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
T _ _ d _ _ _ T _ _ _ d _ _ T EOL
_ D _ _ _ t _ _ _ t _ _ _ D _ EOL
_ _ D _ _ _ d _ d _ _ _ D _ _ EOL
d _ _ D _ _ _ d _ _ _ D _ _ d EOL
_ _ _ _ D _ _ _ _ _ D _ _ _ _ EOL
_ t _ _ _ t _ _ _ t _ _ _ t _ EOL
_ _ d _ _ _ d _ d _ _ _ d _ _ EOL
T _ _ d _ _ _ S _ _ _ d _ _ T EOL
_ _ d _ _ _ d _ d _ _ _ d _ _ EOL
_ t _ _ _ t _ _ _ t _ _ _ t _ EOL
_ _ _ _ D _ _ _ _ _ D _ _ _ _ EOL
d _ _ D _ _ _ d _ _ _ D _ _ d EOL
_ _ D _ _ _ d _ d _ _ _ D _ _ EOL
_ D _ _ _ t _ _ _ t _ _ _ D _ EOL
T _ _ d _ _ _ T _ _ _ d _ _ T
+388
View File
@@ -0,0 +1,388 @@
#!/usr/bin/perl -w
#
# build-data.pl
# Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##########################################################################
#
# The game's data file contains font data followed by a list of 8k blocks,
# each one of which has this format:
# - Unsigned big-endian word giving the number of dictionary words in
# the file.
# - List of dictionary words, where each word is a string that ends
# in a character whose code is >= 0x80. The actual code of the last
# character of the word is this code & 0x7F. Example: "ABC" is
# encoded as "AB\xC3", because 0xC3 & 0x7F = 67 = ord('C').
# - Padding to have each block contain 8192 bytes.
require 5.14.0; # for /r modifier on s///
use strict;
$| = 1; # no buffering on STDOUT
my ($wordListFilename, $dataFilename, $wordLengthIndexFilename,
$minWordLen, $maxWordLen, $maxBlocks);
my $sectorSize = 256; # CoCo floppy sector size
my $mmuBlockLen = 8192; # CoCo 3 MMU block size
my $maxBlockLen = $mmuBlockLen - 2; # 1st word of block gives number of words in block
my $numWrittenBlocks = 0;
my $fhBlock; # data file whose name is in $dataFilename
my $dictStartOffset; # offset in bytes where the dictionary starts in $fhBlock
# Pads $fhBlock to a multiple of the argument.
# Uses $dictStartOffset.
#
sub
padDCTFile
{
my ($size) = @_;
die unless $size > 0;
my $fileLen = tell($fhBlock) - $dictStartOffset;
if ($fileLen < 0)
{
print "ERROR: failed to get writing position in file $dataFilename: $!\n";
exit 1;
}
my $fileLenAfterPadding = int(($fileLen + $size - 1) / $size) * $size;
my $paddingNeeded = $fileLenAfterPadding - $fileLen;
if ($paddingNeeded > 0)
{
print "Padding with $paddingNeeded bytes.\n";
print $fhBlock " " x $paddingNeeded;
}
}
# Receives a reference to an array of words.
# Writes those words to $fhBlock.
# Increments $numWrittenBlocks upon success.
#
sub writeBlock
{
my ($raBlock) = @_;
#print "writeBlock: ", $raBlock->[0], "\n";
my $numWordsInBlock = scalar(@$raBlock);
die unless $numWordsInBlock <= 65535;
print "Writing $numWordsInBlock words to $dataFilename\n";
print $fhBlock pack("n", $numWordsInBlock); # 16-bit big endian
my $wordIndexInBlock = 0;
for my $word (@$raBlock)
{
#print "Word at index $wordIndexInBlock: '$word'\n";
++$wordIndexInBlock;
my $prefix = substr($word, 0, length($word) - 1);
my $lastChar = substr($word, length($word) - 1);
my $encodedWord = $prefix . chr(ord($lastChar) + 0x80);
print $fhBlock $encodedWord;
}
++$numWrittenBlocks;
}
# Sort comparator.
#
sub byDecreasingLength
{
return length($b) <=> length($a);
}
# Parses the hex bytes in a C file and writes the binary data to $fh.
#
sub writeFont($$)
{
my ($fh, $cFilePath) = @_;
my $numBytesWritten = 0;
my $cFile;
if (!open($cFile, $cFilePath))
{
print "$0: ERROR: failed to open $cFilePath: $!\n";
exit 1;
}
while (<$cFile>)
{
# Line example:
# 0xd8, 0x88, 0x78, 0x98, 0xe8, 0x18, 0xd8, 0xf8, // 36 (0x24)
#
s!\s*//.*$!!; # remove any trailing comment
if (/^\s*(0x.*),/)
{
my @bytes = split /,\s*/, $1; # 0xNN, ..., 0xNN
@bytes = map { hex(s/^0x//r) } @bytes; # /r returns modified string instead of success count
my $binary = pack("C*", @bytes);
$numBytesWritten += length($binary);
print $fh $binary; # array of numbers converted to raw binary
}
}
close $cFile;
print "Wrote $numBytesWritten font bytes obtained from $cFilePath\n";
}
sub writeFonts($)
{
my ($fh) = @_;
writeFont($fh, "font4x8-ascii.c");
writeFont($fh, "font5x8-A-Z.c");
padDCTFile($sectorSize); # pad last sector to 256 bytes
}
###############################################################################
die unless @ARGV == 6;
($wordListFilename, $dataFilename, $wordLengthIndexFilename,
$minWordLen, $maxWordLen, $maxBlocks) = @ARGV;
die unless defined $maxBlocks;
# Read the allowed words from $wordListFilename.
#
my $fhWords;
if (!open($fhWords, $wordListFilename))
{
print "$0: ERROR: $wordListFilename: $!\n";
exit 1;
}
my %wordTable; # key: upper-case word; value: 1
my $maxWordLenSeen = 0;
my $numRejectedWords = 0;
while (<$fhWords>)
{
s/\s+$//; # remove trailing white space
tr/a-z/A-Z/; # convert to uppercase
my $len = length($_);
if ($len >= $minWordLen && $len <= $maxWordLen && /^[A-Z]+$/)
{
$maxWordLenSeen = $len if $len > $maxWordLenSeen;
$wordTable{$_} = 1;
}
else
{
#print "Warning: word '$_' rejected.\n";
++$numRejectedWords;
}
}
close $fhWords;
my @selectedWords = sort keys %wordTable;
print "Number of words of lengths $minWordLen..$maxWordLen selected from $wordListFilename: ",
scalar(@selectedWords), "\n";
die unless @selectedWords > 0;
# Dump the selected words in a text file.
#
#open(SELECTED_WORDS, ">build-data-selected-words.txt") or die;
#print SELECTED_WORDS join("\n", @selectedWords), "\n";
#close(SELECTED_WORDS) or die;
print "Length of the longest selected word: $maxWordLenSeen\n";
print "Number of rejected words: $numRejectedWords\n";
die unless $maxWordLenSeen > 0;
# Sort the words from longest to shortest.
#
@selectedWords = sort byDecreasingLength @selectedWords;
# Create the output file.
#
if (!open($fhBlock, "> $dataFilename"))
{
print "$0: ERROR: failed to create $dataFilename: $!\n";
return undef;
}
binmode $fhBlock;
# Write font data (not related to the dictionary) at the start
# of the file.
#
writeFonts($fhBlock);
# Note where the font data ends and the dictionary data is about
# to be written.
#
$dictStartOffset = tell($fhBlock);
die unless $dictStartOffset % 256 == 0;
my @curBlock; # array of words
my $curBlockLen = 0; # length in bytes of current block, whose length must be <= $maxBlockLen;
# this is also the total length of the strings in @curBlock
my $curBlockWordCount = 0; # number of elements in @curBlock
my $totalLen = 0;
my $lenPrevWord; # length of the word processed by preceding iteration
# key: word length; value: {block, wordOffset, offset}.
# Describes the contents of a single block, not the whole dictionary.
# Each entry gets written to file $wordLengthIndexFilename.
#
my %wordLengthIndex;
for my $word (@selectedWords) # for each word in decreasing order of length
{
#print "Word: [$word], lenPrevWord=", $lenPrevWord || -1, "\n";
$totalLen += length($word);
if ($curBlockLen + length($word) > $maxBlockLen) # if no room in current block
{
# Any preceding block must be at an offset that is
# a multiple of 8192 bytes.
padDCTFile($mmuBlockLen);
writeBlock(\@curBlock);
# Reinit block.
@curBlock = ();
$curBlockLen = 0;
$curBlockWordCount = 0;
}
# If currentword has different length than previous one,
# declare some array entries.
#
if (!defined $lenPrevWord || length($word) != $lenPrevWord)
{
my $firstLenToDo = (defined $lenPrevWord ? $lenPrevWord - 1 : length($word));
my $lastLenToDo = length($word);
# Declare entries concerning word lengths $firstLenToDo to $lastLenToDo inclusively.
for (my $wlen = $firstLenToDo; $wlen >= $lastLenToDo; --$wlen)
{
print "Words of length $wlen start in block #",
$numWrittenBlocks, ", at word offset $curBlockWordCount, byte offset $curBlockLen\n";
$wordLengthIndex{$wlen} = {
block => $numWrittenBlocks,
wordOffset => $curBlockWordCount,
offset => $curBlockLen # byte offset
};
}
}
#print "Before: '", $curBlock[0], "', ", scalar(@curBlock), "\n";
push @curBlock, $word;
#print "First: '", $curBlock[0], "', ", scalar(@curBlock), "\n";
$curBlockLen += length($word);
++$curBlockWordCount;
$lenPrevWord = length($word);
}
# Complete %wordLengthIndex.
#
{
die unless defined $lenPrevWord;
die unless defined $minWordLen;
my $firstLenToDo = $lenPrevWord - 1;
my $lastLenToDo = $minWordLen - 1;
for (my $wlen = $firstLenToDo; $wlen >= $lastLenToDo; --$wlen)
{
print "Words of length ", $wlen + 1, " end at block #",
$numWrittenBlocks,
", at word offset $curBlockWordCount, byte offset $curBlockLen\n";
$wordLengthIndex{$wlen} = {
block => $numWrittenBlocks, # zero-based block index
wordOffset => $curBlockWordCount,
offset => $curBlockLen
};
}
}
# Write the last block, if any.
#
if ($curBlockLen > 0)
{
padDCTFile($mmuBlockLen);
writeBlock(\@curBlock);
}
# The last block only needs to be padded to a multiple of 256 bytes.
# This ends the last sector with defined bytes instead of garbage.
#
padDCTFile($sectorSize);
# Close the output file.
#
if (!close($fhBlock))
{
print "$0: ERROR: failed to close $dataFilename: $!\n";
exit 1;
}
print "Total length of the selected words: $totalLen characters\n";
print "Number of MMU blocks: $numWrittenBlocks\n";
print "Word count in last block: $curBlockWordCount\n";
print "Length of last block: $curBlockLen\n";
# Create a C file containing an array.
#
print "Creating $wordLengthIndexFilename\n";
open(W, "> $wordLengthIndexFilename") or die;
print W <<__EOF__;
/* Generated by build-data.pl. Do not edit. */
#include "defs.h"
const WordLengthRecord wordLengthRecords[] =
{
__EOF__
# An entry is written for length 1 because it indicates
# where the list of words of length 2 ends.
#
for my $len (1..$maxWordLenSeen)
{
my $rh = $wordLengthIndex{$len};
die "len=$len" unless defined $rh->{block};
die unless $rh->{offset} <= $maxBlockLen;
printf W " { %2u, %4u, %4u }, /* length %u */\n",
$rh->{block}, $rh->{wordOffset}, $rh->{offset}, $len;
}
print W <<__EOF__;
};
__EOF__
printf W "const byte numWordLengthRecords = %u;\n", $maxWordLenSeen;
close(W) or die;
if ($numWrittenBlocks > $maxBlocks)
{
print "$0: ERROR: Exceeded maximum number of blocks (wrote $numWrittenBlocks, max is $maxBlocks).\n";
exit 1;
}
+176
View File
@@ -0,0 +1,176 @@
/* defs.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_defs
#define _H_defs
#include <coco.h>
#if 0
#include <assert.h>
#else
#ifndef NDEBUG
void assertHandler(const char *file, int lineno, const char *condition);
#define assert(cond) do { if (!(cond)) assertHandler(__FILE__, __LINE__, ""); } while (0)
#define static_assert(cond) typedef char CONCAT(_StaticAssertDummyArray_, __LINE__)[(cond) ? 1 : -1]
#else
#define assert(cond) ((void) 0)
#define static_assert(cond) ((void) 0)
#endif
#define CONCAT2(a, b) a ## b
#define CONCAT(a, b) CONCAT2(a, b)
#endif
// STRINGIFY(FOO) gives "FOO".
//
#define STRINGIFY(x) #x
// If we have #define FOO 42
// then STRINGIFY_VALUE(FOO) gives "42".
//
#define STRINGIFY_VALUE(x) STRINGIFY(x)
#ifndef MAX_NUM_DICT_BLOCKS
#error "MAX_NUM_DICT_BLOCKS not defined."
#endif
#ifndef MIN_WORD_LEN
#error "MIN_WORD_LEN not defined."
#endif
#ifndef MAX_WORD_LEN
#error "MAX_WORD_LEN not defined."
#endif
// See HACKING.md for a memory map.
enum
{
NUM_DISK_DRIVES = 1,
IRQ_VECTOR = 0xFFF8,
TEXT_SCREEN = 0xE000, // 32x16 and 40x24 hardware text screen buffer
FONT_4x8_BUFFER = TEXT_SCREEN + 40 * 24, // contains bytes defined in font4x8-ascii.c
FONT_4x8_SECTORS = 3, // number of sectors to read to fill that buffer
FONT_5x8_BUFFER = FONT_4x8_BUFFER + FONT_4x8_SECTORS * 256, // contains bytes defined in font5x8-ascii.c
FONT_5x8_SECTORS = 1, // number of sectors to read to fill that buffer
STACK_BOTTOM = 0xFEEE,
BLOCK_SIZE = 8192, // size in bytes of a GIME MMU block
BREAK_KEY = 3,
// Graphics:
NUM_GRAPHICS_BLOCKS = 3, // 256x192x16 takes three 8k blocks
SCRN_WIDTH = 256u, // in pixels
SCRN_HEIGHT = 192u, // in pixels
NUM_COLORS = 16, // number of CoCo 3 palette slots
BYTES_PER_ROW = SCRN_WIDTH / 2,
CHAR_WIDTH = 5, // number of pixels per graphics text window character column
CHAR_HEIGHT = 8, // number of pixels per graphics text window character row
TEXT_SCREEN_WIDTH = 51, // in characters
TEXT_SCREEN_HEIGHT = 24,
TEXT_WIN_LEFT = 37, // leftmost 51x24 screen column of text window (at right of board)
TEXT_WIN_TOP = 18,
TEXT_WIN_WIDTH = TEXT_SCREEN_WIDTH - TEXT_WIN_LEFT, // in characters
TEXT_WIN_HEIGHT = TEXT_SCREEN_HEIGHT - TEXT_WIN_TOP,
TEXT_TURN_ROW = 3, // text row where "Your/My turn" is written
TEXT_RESULT_ROW = 5,
TEXT_INSTR_ROW = 10, // instructions
TEXT_SCORE_ROW = 16,
// Hardware text mode (no color attributes):
HW_TEXT_SCREEN_WIDTH = 40,
HW_TEXT_SCREEN_HEIGHT = 24,
HW_TEXT_SCREEN_BUFFER = 0xE000,
HW_TEXT_SCREEN_BACK_COLOR = 0,
HW_TEXT_SCREEN_FORE_COLOR = 63,
// Game:
BOARD_SIZE = 15, // number of board rows and columns
TILE_WIDTH = 12, // in pixels
TILE_HEIGHT = 12, // in pixels
NUM_TILE_TYPES = 27, // A..Z plus blank
RACK_SIZE = 7, // maximum number of tiles in a player's rack
TILE_TYPE_NONE = 255,
TILE_TYPE_BLANK = 0,
NUM_BLANK_TILES = 2,
NUM_PLAYERS = 2,
LEVEL_EASY = 0,
LEVEL_HARD = 1,
// CoCo 3 memory blocks. (A 128k machine has blocks 48..63.)
FIRST_GRAPHICS_BLOCK = 51, // graphics in 51..53
GRAPHICS_START = FIRST_GRAPHICS_BANK * BLOCK_SIZE,
GRAPHICS_END = GRAPHICS_START + SCRN_WIDTH * SCRN_HEIGHT / 2,
// SCRN_* need to be unsigned for this computation to work.
// CoCo 3 memory banks (0..7).
DICT_BANK = 0,
FIRST_GRAPHICS_BANK = 4,
// Palette values.
PAL_POS_CURSOR = PAL_BOARD_WRITING,
PAL_BLANK_TILE_FORE = PAL_BOARD_BG,
};
// Board square types.
//
enum
{
SQ_EMPTY,
SQ_START,
SQ_TRIPLE_WORD,
SQ_DOUBLE_WORD,
SQ_TRIPLE_LETTER,
SQ_DOUBLE_LETTER
};
typedef interrupt void (*ISR)(void);
// Gives a number of elements, not a number of bytes.
//
#define ARRAY_SIZE(array) (sizeof(array) / sizeof((array)[0]))
#define ARRAY_END(array) ((array) + ARRAY_SIZE(array))
#define poke(address, byteValue) (* (byte *) (address) = (byteValue))
#define pokeWord(address, wordValue) (* (word *) (address) = (wordValue))
#define mmuSet(bank, block) (poke(0xFFA0 + (bank), (block)))
typedef struct WordLengthRecord
{
byte blockNo; // MMU block that contains dictionary data;
// (0 .. MAX_NUM_DICT_BLOCKS - 2)
word wordOffset; // in dictionary words, from start of MMU block
word offset; // in bytes, from start of MMU block
} WordLengthRecord;
// Array that is defined in word-length-index.c, generated by build-data.pl.
//
extern const WordLengthRecord wordLengthRecords[];
extern const byte numWordLengthRecords; // number of elements in wordLengthRecords[]
#endif /* _H_defs */
+413
View File
@@ -0,0 +1,413 @@
/* dict.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dict.h"
#include "file.h"
// See dict_setSearchProgressCallback().
//
static void (*dict_searchProgressCallback)(void);
void
dict_setSearchProgressCallback(void (*functor)(void))
{
dict_searchProgressCallback = functor;
}
static byte numDictBlocks; // index into dictMMUBlockIndexes[]
// See memory map in HACKING.md.
//
static const byte dictMMUBlockIndexes[MAX_NUM_DICT_BLOCKS] =
{
48, 49, 50, 54, 55, 56, 60, 61, 62
};
typedef struct DataFileReader
{
DECBFile *file;
word fileSectorIndex; // zero-based sector number in 'file'
const word numFileSectors; // length of 'file' in sectors
byte **textScrnWritePos; // used to reposition 32x16 cursor
byte *progressionPos; // position where progression % gets written
} DataFileReader;
// Returns a DECB_* error code.
//
static byte
readSector(DataFileReader *fileReader, byte *sectorDest)
{
byte err = decb_readSector(fileReader->file, sectorDest, fileReader->fileSectorIndex);
if (err != DECB_OK)
{
printf("\nFAILED TO READ SECTOR TO %p: ERROR %u\n", sectorDest, err);
return err;
}
// Reposition cursor at the screen position of the
// progression percentage, and update it.
//
*fileReader->textScrnWritePos = fileReader->progressionPos;
printf("%3u%%", (fileReader->fileSectorIndex + 1) * 100
/ fileReader->numFileSectors);
return DECB_OK;
}
// Reads 'numSectors' from 'fileReader' into 'dest'.
//
static byte
loadFontData(DataFileReader *fileReader, byte *dest, byte numSectors)
{
for (byte i = 0; i < numSectors; ++i, ++fileReader->fileSectorIndex, dest += 256)
{
byte err = readSector(fileReader, dest);
if (err != DECB_OK)
return err;
}
return DECB_OK;
}
// Initializes numDictBlocks.
//
static byte
loadDictionarySectors(DataFileReader *fileReader)
{
// For each MMU block to fill.
//
for (numDictBlocks = 0;
numDictBlocks < MAX_NUM_DICT_BLOCKS && fileReader->fileSectorIndex < fileReader->numFileSectors;
++numDictBlocks)
{
// Tune in the next MMU block to fill, at address
// DICT_BANK * BLOCK_SIZE.
//
const byte mmuBlockIndex = dictMMUBlockIndexes[numDictBlocks];
mmuSet(DICT_BANK, mmuBlockIndex);
// Start a writing pointer at the start of the MMU block to fill.
//
byte *sectorDest = (byte *) (DICT_BANK * BLOCK_SIZE);
// For each 256-byte page in the current MMU block,
// but without going past the file's last sector.
//
for (byte i = 0;
i < BLOCK_SIZE / 256 && fileReader->fileSectorIndex < fileReader->numFileSectors;
++i, ++fileReader->fileSectorIndex, sectorDest += 256)
{
byte err = readSector(fileReader, sectorDest);
if (err != DECB_OK)
return err;
// Check the first 16 bits of an MMU block, which must contain
// the number of words in that block. A block being 8192 bytes,
// there cannot be more than 8192 words in a block.
//
assert(i != 0 || * (word *) sectorDest <= BLOCK_SIZE);
}
} // for
return DECB_OK;
}
// Initializes numDictBlocks.
//
BOOL
loadDataFile(byte driveNo, byte **textScrnWritePos)
{
printf("LOADING DICTIONARY... ");
// Position where the progression percentage will be displayed.
//
byte *progressionPos = *textScrnWritePos;
const char *filename = DATA_FILENAME; // defined with -D in Makefile
DECBFile file;
byte err = decb_openSectorFile(&file, driveNo, filename);
if (err != DECB_OK)
{
printf("\nFAILED TO OPEN %s: ERROR %u\n", filename, err);
return FALSE;
}
// Get the number of sectors in the file.
//
byte lastFileGranule;
word numFileSectors = 0;
byte numGranules = decb_getNumGranulesInOpenFile(&file, &lastFileGranule, &numFileSectors);
if (numGranules == 0xFF || numFileSectors == 0)
{
printf("\nFAILED TO GET FILE SIZE\n");
err = DECB_ERR_CORRUPT_DIR;
}
else
{
DataFileReader fileReader = { &file, 0, numFileSectors,
textScrnWritePos, progressionPos };
// Load font data (not related to dictionary).
//
err = loadFontData(&fileReader, (byte *) FONT_4x8_BUFFER, FONT_4x8_SECTORS);
if (err == DECB_OK)
{
assert(fileReader.fileSectorIndex == FONT_4x8_SECTORS);
err = loadFontData(&fileReader, (byte *) FONT_5x8_BUFFER, FONT_5x8_SECTORS);
if (err == DECB_OK)
{
assert(fileReader.fileSectorIndex == FONT_4x8_SECTORS + FONT_5x8_SECTORS);
// Load the dictionary into MMU blocks.
//
err = loadDictionarySectors(&fileReader);
}
}
}
putchar('\n');
byte closeErr = decb_closeSectorFile(&file);
if (closeErr != DECB_OK)
{
printf("\nFAILED TO CLOSE %s: ERROR %u\n", filename, err);
return FALSE;
}
return err == DECB_OK;
}
// src: Must point to a high-bit terminated string.
// Writes a NUL-terminated string in dest[].
//
static byte
decodeWord(const byte *src, char dest[MAX_WORD_LEN + 1])
{
for (const byte *reader = src; ; )
{
byte ch = *reader++;
if (ch & 0x80) // if last char
{
*dest++ = (char) (ch & 0x7F);
*dest = '\0';
return (byte) (reader - src);
}
*dest++ = (char) ch;
}
}
BOOL
iterateDictionary(ProcessDictBlockFuncPtr processNextBlock,
ProcessDictWordFuncPtr processDictWord,
byte wordLength,
void *userData)
{
//printf("itD(wL=%u): nWLR=%u; ", wordLength, numWordLengthRecords);
byte b; // starting block no (0 .. MAX_NUM_DICT_BLOCKS - 1)
byte lastBlock; // last block (inclusively) to process
word startWordOffset; // in words
word startOffset; // in bytes (0 .. BLOCK_SIZE - 2)
word endWordOffset; // in words
// If the word length is not zero and within the possible word lengths found in the dictionary,
// then restrict the search to words of that length.
//
if (wordLength >= MIN_WORD_LEN
&& wordLength < numWordLengthRecords + (MIN_WORD_LEN - 1))
{
const WordLengthRecord *startRecord = &wordLengthRecords[wordLength - (MIN_WORD_LEN - 1)];
b = startRecord->blockNo;
//printf("b=%u; ", b);
assert(b < MAX_NUM_DICT_BLOCKS);
startWordOffset = startRecord->wordOffset;
startOffset = startRecord->offset;
//printf("startOffset=%u; ", startOffset);
assert(startOffset <= BLOCK_SIZE);
const WordLengthRecord *endRecord = &wordLengthRecords[wordLength - MIN_WORD_LEN];
lastBlock = endRecord->blockNo;
endWordOffset = endRecord->wordOffset;
}
else // search the entire dictionary:
{
b = 0;
lastBlock = numDictBlocks - 1;
startWordOffset = 0;
startOffset = 0;
endWordOffset = 0xFFFF;
}
//printf("iterateDictionary: lastBlock=%u, startWordOffset=%u, endWordOffset=%u\n", lastBlock, startWordOffset, endWordOffset);
assert(lastBlock < MAX_NUM_DICT_BLOCKS);
for ( ; b <= lastBlock; ++b)
{
const byte mmuBlockIndex = dictMMUBlockIndexes[b];
mmuSet(DICT_BANK, mmuBlockIndex);
const byte *block = (unsigned) (DICT_BANK * BLOCK_SIZE);
word numWordsInBlock = * (word *) block;
//printf("iterateDictionary: b=%u, numWordsInBlock=%u\n", b, numWordsInBlock);
if (processNextBlock)
{
byte action = (*processNextBlock)(numWordsInBlock, userData);
if (action == DICT_ITER_STOP)
return FALSE;
if (action == DICT_ITER_NEXT_BLOCK)
continue;
assert(action == DICT_ITER_LIST_WORDS);
mmuSet(DICT_BANK, mmuBlockIndex); // callback invocation may have changed DICT_BANK slot (e.g., recursive search)
}
if (processDictWord)
{
const byte *wordPtr = block + 2 + startOffset;
word endWordOffsetThisBlock = (endWordOffset == 0xFFFF || b < lastBlock
? * (word *) block
: endWordOffset);
//printf("iterateDictionary: b=%u, endWordOffsetThisBlock=%u\n", b, endWordOffsetThisBlock);
for (word w = startWordOffset; w < endWordOffsetThisBlock; ++w)
{
char currentWord[MAX_WORD_LEN + 1];
byte wordLen = decodeWord(wordPtr, currentWord);
//printf("[%s]\n", currentWord);
// Invoke the callback on the decoded word.
// Stop the iteration if the callback asks for that.
// This callback is allowed to change the block tuned in to DICT_BANK,
// namely if it does a recursive iteration.
//
if (!(*processDictWord)(currentWord, wordLen, userData))
return FALSE;
mmuSet(DICT_BANK, mmuBlockIndex); // callback invocation may have changed DICT_BANK slot (e.g., recursive search)
wordPtr += wordLen;
}
}
// Start next block at its beginning.
startWordOffset = 0;
startOffset = 0;
}
return TRUE;
}
static __gcccall asm BOOL
equalStrings(const char *a, const char *b)
{
asm
{
; N.B.: This code is not appropriate under OS-9, where Y must
; be preserved, as it points to the data segment of the
; current process.
;
; X contains 'a', as per __gcccall.
;
ldy 2,s ; 'b'
@loop
ldb ,x+ ; read char from 'a'
cmpb ,y+ ; compare to char from 'b'
bne @returnFalse
;
tstb
bne @loop
;
ldb #1
rts
@returnFalse
clrb
}
}
typedef struct Lookup
{
const char *candidateWord;
byte length;
byte blockNo;
BOOL found; // must be initialized to FALSE
} Lookup;
static BOOL
compareWords(const char *currentWord, byte currentWordLength, void *userData)
{
Lookup *lookup = (Lookup *) userData;
//printf("compareWords: currentWord='%s' (%u)\n", currentWord, currentWordLength);
// Show a progress indicator, if the callback for it has been registered.
//
static byte timeToShowProgress = 0;
if (dict_searchProgressCallback && ++timeToShowProgress == 0)
(*dict_searchProgressCallback)();
// If the current word is shorter than the candidate word, then fail,
// because all of the following words are also shorter than the candidate word.
if (currentWordLength < lookup->length)
{
//printf("compareWords: FALSE b/c %u < %u\n", currentWordLength, lookup->length);
return FALSE; // stop iteration and leave lookup->found at FALSE
}
if (equalStrings(currentWord, lookup->candidateWord)) // if match
{
//printf("compareWords: TRUE (found)\n");
lookup->found = TRUE;
return FALSE; // stop iteration
}
return TRUE; // continue iteration
}
BOOL
isWordInDictionary(const char *candidateWord)
{
byte candidateWordLen = (byte) strlen(candidateWord);
if (candidateWordLen < MIN_WORD_LEN || candidateWordLen > MAX_WORD_LEN)
return FALSE;
Lookup lookup = { candidateWord, candidateWordLen, 0, FALSE };
(void) iterateDictionary(NULL, compareWords, lookup.length, &lookup);
return lookup.found;
}
static byte
getStatsFunctor(word numWordsInBlock, void *userData)
{
//printf("getStatsFunctor(%u, %p)\n", numWordsInBlock, userData, );
** (word **) userData += numWordsInBlock;
return DICT_ITER_NEXT_BLOCK;
}
void
getDictionaryStats(word *totalNumWords)
{
*totalNumWords = 0;
if (!iterateDictionary(getStatsFunctor, NULL, 0, (void *) &totalNumWords))
assert(FALSE);
}
+88
View File
@@ -0,0 +1,88 @@
/* dict.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_dict
#define _H_dict
#include "defs.h"
// See iterateDictionary().
//
typedef byte (*ProcessDictBlockFuncPtr)(word numWordsInBlock, void *userData);
// See iterateDictionary().
// Must not assume that the 'currentWord' pointer will be valid
// after the call to this function has returned.
//
typedef BOOL (*ProcessDictWordFuncPtr)(const char *currentWord, byte currentWordLength, void *userData);
// Loads the data file into memory, including font data and the dictionary.
// driveNo: Drive where that file is.
// textScrnWritePos: Pointer to the cursor pointer. Assigning to that pointer
// must reposition the cursor used by printf().
// Returns true upon success.
//
BOOL loadDataFile(byte driveNo, byte **textScrnWritePos);
// See iterateDictionary().
//
enum
{
DICT_ITER_STOP, // stop the iteration
DICT_ITER_NEXT_BLOCK, // jump to the next block (do not call ProcessDictWordFuncPtr)
DICT_ITER_LIST_WORDS // call ProcessDictWordFuncPtr on each word in the current block
};
// Sets the callback that is invoked periodically during a call to
// isWordInDictionary(). Allowed to be null.
//
void dict_setSearchProgressCallback(void (*functor)(void));
// processDictBlock: If not null, invoked for each MMU block that contains dictionary data.
// Must return one of the DICT_ITER_* enum names above.
// processDictWord: Invoked for each word in the current MMU block, after processDictBlock
// has been invoked, and only if the latter returned DICT_ITER_LIST_WORDS.
// If null, then processDictBlock must NOT return DICT_ITER_LIST_WORDS.
// wordLength: If not zero, restrict the search to words of this length.
// userData: Pointer passed to the callbacks.
// Returns TRUE if the iteration reached the end, FALSE otherwise, i.e.,
// one of the two callbacks returned a value that requested stopping the iteration.
//
// A callback is allowed to start a sub-iteration by making its own call
// to iterateDictionary().
//
BOOL iterateDictionary(ProcessDictBlockFuncPtr processDictBlock,
ProcessDictWordFuncPtr processDictWord,
byte wordLength,
void *userData);
// See also dict_setSearchProgressCallback().
//
BOOL isWordInDictionary(const char *candidateWord);
void getDictionaryStats(word *totalNumWords);
#endif /* _H_dict */
+35
View File
@@ -0,0 +1,35 @@
/* file.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "file.h"
#include "defs.h"
BOOL
initDiskSystem(DECBDrive drives[])
{
decb_init(drives, NUM_DISK_DRIVES);
for (byte driveNo = 0; driveNo < NUM_DISK_DRIVES; ++driveNo)
if (decb_registerDrive(driveNo) != DECB_OK)
{
printf("FAILED TO REGISTER DRIVE %u\n", driveNo);
return FALSE;
}
return TRUE;
}
+28
View File
@@ -0,0 +1,28 @@
/* file.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_file
#define _H_file
#include "decbfile.h"
#include "dskcon-standalone.h"
BOOL initDiskSystem(DECBDrive drives[]);
#endif /* _H_file */
+108
View File
@@ -0,0 +1,108 @@
/* font4x8.c - ISO-8859-1 font for a 51x24 software text screen, modified from hirestxt.
By Pierre Sarrazin <http://sarrazip.com/>
This file is in the public domain.
*/
#include "font4x8-ascii.h"
const unsigned char font4x8_ascii[(127 - ' ' + 1) * 8] =
{
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, // 32 (0x20)
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xf8, 0xd8, 0xf8, // 33 (0x21)
0xa8, 0xa8, 0xa8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, // 34 (0x22)
0x98, 0x98, 0x08, 0x98, 0x08, 0x98, 0x98, 0xf8, // 35 (0x23)
0xd8, 0x88, 0x78, 0x98, 0xe8, 0x18, 0xd8, 0xf8, // 36 (0x24)
0xf8, 0x28, 0x28, 0xd8, 0xb8, 0x48, 0x48, 0xf8, // 37 (0x25)
0xb8, 0x58, 0xb8, 0x78, 0x28, 0x58, 0xa8, 0xf8, // 38 (0x26)
0xd8, 0xd8, 0xb8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, // 39 (0x27)
0xe8, 0xd8, 0xb8, 0xb8, 0xb8, 0xd8, 0xe8, 0xf8, // 40 (0x28)
0x78, 0xb8, 0xd8, 0xd8, 0xd8, 0xb8, 0x78, 0xf8, // 41 (0x29)
0xf8, 0x68, 0x98, 0x98, 0x98, 0x68, 0xf8, 0xf8, // 42 (0x2a)
0xf8, 0xd8, 0xd8, 0x88, 0xd8, 0xd8, 0xf8, 0xf8, // 43 (0x2b)
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xd8, 0xd8, 0xb8, // 44 (0x2c)
0xf8, 0xf8, 0xf8, 0x08, 0xf8, 0xf8, 0xf8, 0xf8, // 45 (0x2d)
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0x98, 0x98, 0xf8, // 46 (0x2e)
0xf8, 0xe8, 0xe8, 0xd8, 0xb8, 0x78, 0x78, 0xf8, // 47 (0x2f)
0x98, 0x68, 0x48, 0x28, 0x68, 0x68, 0x98, 0xf8, // 48 (0x30)
0xd8, 0x98, 0xd8, 0xd8, 0xd8, 0xd8, 0x88, 0xf8, // 49 (0x31)
0x98, 0x68, 0xe8, 0x98, 0x78, 0x78, 0x08, 0xf8, // 50 (0x32)
0x98, 0x68, 0xe8, 0x98, 0xe8, 0x68, 0x98, 0xf8, // 51 (0x33)
0xe8, 0xc8, 0xa8, 0x68, 0x08, 0xe8, 0xe8, 0xf8, // 52 (0x34)
0x08, 0x78, 0x78, 0x18, 0xe8, 0xe8, 0x18, 0xf8, // 53 (0x35)
0x98, 0x68, 0x78, 0x18, 0x68, 0x68, 0x98, 0xf8, // 54 (0x36)
0x08, 0xe8, 0xe8, 0xd8, 0xb8, 0xb8, 0xb8, 0xf8, // 55 (0x37)
0x98, 0x68, 0x68, 0x98, 0x68, 0x68, 0x98, 0xf8, // 56 (0x38)
0x98, 0x68, 0x68, 0x88, 0xe8, 0x68, 0x98, 0xf8, // 57 (0x39)
0xf8, 0xf8, 0x98, 0x98, 0xf8, 0x98, 0x98, 0xf8, // 58 (0x3a)
0xf8, 0xf8, 0x98, 0x98, 0xf8, 0xd8, 0xd8, 0xb8, // 59 (0x3b)
0xe8, 0xd8, 0xb8, 0x78, 0xb8, 0xd8, 0xe8, 0xf8, // 60 (0x3c)
0xf8, 0xf8, 0xf8, 0x08, 0xf8, 0x08, 0xf8, 0xf8, // 61 (0x3d)
0x78, 0xb8, 0xd8, 0xe8, 0xd8, 0xb8, 0x78, 0xf8, // 62 (0x3e)
0x98, 0x68, 0xe8, 0xd8, 0xd8, 0xf8, 0xd8, 0xf8, // 63 (0x3f)
0x98, 0x68, 0xe8, 0x88, 0x68, 0x68, 0x98, 0xf8, // 64 (0x40)
0x98, 0x68, 0x68, 0x08, 0x68, 0x68, 0x68, 0xf8, // 65 (0x41)
0x18, 0x68, 0x68, 0x18, 0x68, 0x68, 0x18, 0xf8, // 66 (0x42)
0x98, 0x68, 0x78, 0x78, 0x78, 0x68, 0x98, 0xf8, // 67 (0x43)
0x18, 0x68, 0x68, 0x68, 0x68, 0x68, 0x18, 0xf8, // 68 (0x44)
0x08, 0x78, 0x78, 0x18, 0x78, 0x78, 0x08, 0xf8, // 69 (0x45)
0x08, 0x78, 0x78, 0x18, 0x78, 0x78, 0x78, 0xf8, // 70 (0x46)
0x98, 0x68, 0x78, 0x78, 0x48, 0x68, 0x98, 0xf8, // 71 (0x47)
0x68, 0x68, 0x68, 0x08, 0x68, 0x68, 0x68, 0xf8, // 72 (0x48)
0x88, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x88, 0xf8, // 73 (0x49)
0xc8, 0xe8, 0xe8, 0xe8, 0xe8, 0x68, 0x98, 0xf8, // 74 (0x4a)
0x68, 0x58, 0x38, 0x78, 0x38, 0x58, 0x68, 0xf8, // 75 (0x4b)
0x78, 0x78, 0x78, 0x78, 0x78, 0x78, 0x08, 0xf8, // 76 (0x4c)
0x68, 0x08, 0x08, 0x68, 0x68, 0x68, 0x68, 0xf8, // 77 (0x4d)
0x68, 0x28, 0x48, 0x68, 0x68, 0x68, 0x68, 0xf8, // 78 (0x4e)
0x98, 0x68, 0x68, 0x68, 0x68, 0x68, 0x98, 0xf8, // 79 (0x4f)
0x18, 0x68, 0x68, 0x18, 0x78, 0x78, 0x78, 0xf8, // 80 (0x50)
0x98, 0x68, 0x68, 0x68, 0x68, 0x58, 0xa8, 0xf8, // 81 (0x51)
0x18, 0x68, 0x68, 0x18, 0x68, 0x68, 0x68, 0xf8, // 82 (0x52)
0x98, 0x68, 0x78, 0x98, 0xe8, 0x68, 0x98, 0xf8, // 83 (0x53)
0x88, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xf8, // 84 (0x54)
0x68, 0x68, 0x68, 0x68, 0x68, 0x68, 0x98, 0xf8, // 85 (0x55)
0x68, 0x68, 0x68, 0x68, 0x58, 0x58, 0xb8, 0xf8, // 86 (0x56)
0x68, 0x68, 0x68, 0x68, 0x08, 0x08, 0x68, 0xf8, // 87 (0x57)
0x68, 0x68, 0x68, 0x98, 0x68, 0x68, 0x68, 0xf8, // 88 (0x58)
0xa8, 0xa8, 0xa8, 0xd8, 0xd8, 0xd8, 0xd8, 0xf8, // 89 (0x59)
0x08, 0xe8, 0xd8, 0xb8, 0x78, 0x78, 0x08, 0xf8, // 90 (0x5a)
0x88, 0xb8, 0xb8, 0xb8, 0xb8, 0xb8, 0x88, 0xf8, // 91 (0x5b)
0xf8, 0x78, 0x78, 0xb8, 0xd8, 0xe8, 0xe8, 0xf8, // 92 (0x5c)
0x18, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x18, 0xf8, // 93 (0x5d)
0xd8, 0xa8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, // 94 (0x5e)
0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0x08, 0xf8, // 95 (0x5f)
0xb8, 0xb8, 0xd8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, // 96 (0x60)
0xf8, 0xf8, 0x98, 0xe8, 0x88, 0x68, 0x08, 0xf8, // 97 (0x61)
0x78, 0x78, 0x18, 0x68, 0x68, 0x68, 0x18, 0xf8, // 98 (0x62)
0xf8, 0xf8, 0x88, 0x78, 0x78, 0x78, 0x88, 0xf8, // 99 (0x63)
0xe8, 0xe8, 0x88, 0x68, 0x68, 0x68, 0x88, 0xf8, // 100 (0x64)
0xf8, 0xf8, 0x98, 0x68, 0x08, 0x78, 0x98, 0xf8, // 101 (0x65)
0xc8, 0xb8, 0xb8, 0x08, 0xb8, 0xb8, 0xb8, 0xf8, // 102 (0x66)
0xf8, 0xf8, 0x88, 0x68, 0x68, 0x08, 0xe8, 0x18, // 103 (0x67)
0x78, 0x78, 0x18, 0x68, 0x68, 0x68, 0x68, 0xf8, // 104 (0x68)
0xd8, 0xf8, 0x98, 0xd8, 0xd8, 0xd8, 0x88, 0xf8, // 105 (0x69)
0xd8, 0xf8, 0x98, 0xd8, 0xd8, 0xd8, 0xd8, 0x38, // 106 (0x6a)
0x78, 0x78, 0x68, 0x58, 0x38, 0x58, 0x68, 0xf8, // 107 (0x6b)
0x98, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0x88, 0xf8, // 108 (0x6c)
0xf8, 0xf8, 0x18, 0x08, 0x08, 0x68, 0x68, 0xf8, // 109 (0x6d)
0xf8, 0xf8, 0x18, 0x68, 0x68, 0x68, 0x68, 0xf8, // 110 (0x6e)
0xf8, 0xf8, 0x98, 0x68, 0x68, 0x68, 0x98, 0xf8, // 111 (0x6f)
0xf8, 0xf8, 0x18, 0x68, 0x68, 0x18, 0x78, 0x78, // 112 (0x70)
0xf8, 0xf8, 0x88, 0x68, 0x68, 0x88, 0xe8, 0xe8, // 113 (0x71)
0xf8, 0xf8, 0x18, 0x68, 0x78, 0x78, 0x78, 0xf8, // 114 (0x72)
0xf8, 0xf8, 0x88, 0x78, 0x98, 0xe8, 0x18, 0xf8, // 115 (0x73)
0xb8, 0xb8, 0x08, 0xb8, 0xb8, 0xb8, 0xc8, 0xf8, // 116 (0x74)
0xf8, 0xf8, 0x68, 0x68, 0x68, 0x68, 0x88, 0xf8, // 117 (0x75)
0xf8, 0xf8, 0x68, 0x68, 0x68, 0x58, 0xb8, 0xf8, // 118 (0x76)
0xf8, 0xf8, 0x68, 0x68, 0x08, 0x08, 0x18, 0xf8, // 119 (0x77)
0xf8, 0xf8, 0x68, 0x68, 0x98, 0x68, 0x68, 0xf8, // 120 (0x78)
0xf8, 0xf8, 0x68, 0x68, 0x68, 0x88, 0xe8, 0x18, // 121 (0x79)
0xf8, 0xf8, 0x08, 0xd8, 0xb8, 0x78, 0x08, 0xf8, // 122 (0x7a)
0xe8, 0xd8, 0xd8, 0xb8, 0xd8, 0xd8, 0xe8, 0xf8, // 123 (0x7b)
0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xd8, 0xf8, // 124 (0x7c)
0x78, 0xb8, 0xb8, 0xd8, 0xb8, 0xb8, 0x78, 0xf8, // 125 (0x7d)
0xa8, 0x58, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, 0xf8, // 126 (0x7e)
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // 127 (0x7f) [Filled rectangle]
};
+38
View File
@@ -0,0 +1,38 @@
/* font5x8_A_Z.c - Upper-case letter 5x7 font.
By Pierre Sarrazin <http://sarrazip.com/>
This file is in the public domain.
*/
#include "font5x8-A-Z.h"
const unsigned char font5x8_A_Z[26 * 8] =
{
0xdc, 0xac, 0x74, 0x74, 0x04, 0x74, 0x74, 0xfc, // 65 (0x41)
0x0c, 0x74, 0x74, 0x0c, 0x74, 0x74, 0x0c, 0xfc, // 66 (0x42)
0x8c, 0x74, 0x7c, 0x7c, 0x7c, 0x74, 0x8c, 0xfc, // 67 (0x43)
0x0c, 0x74, 0x74, 0x74, 0x74, 0x74, 0x0c, 0xfc, // 68 (0x44)
0x04, 0x7c, 0x7c, 0x0c, 0x7c, 0x7c, 0x04, 0xfc, // 69 (0x45)
0x04, 0x7c, 0x7c, 0x0c, 0x7c, 0x7c, 0x7c, 0xfc, // 70 (0x46)
0x8c, 0x74, 0x7c, 0x64, 0x74, 0x74, 0x8c, 0xfc, // 71 (0x47)
0x74, 0x74, 0x74, 0x04, 0x74, 0x74, 0x74, 0xfc, // 72 (0x48)
0x8c, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, 0x8c, 0xfc, // 73 (0x49)
0xf4, 0xf4, 0xf4, 0xf4, 0xf4, 0x74, 0x8c, 0xfc, // 74 (0x4a)
0x74, 0x6c, 0x5c, 0x3c, 0x5c, 0x6c, 0x74, 0xfc, // 75 (0x4b)
0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x7c, 0x04, 0xfc, // 76 (0x4c)
0x74, 0x24, 0x54, 0x74, 0x74, 0x74, 0x74, 0xfc, // 77 (0x4d)
0x74, 0x34, 0x34, 0x54, 0x64, 0x64, 0x74, 0xfc, // 78 (0x4e)
0x8c, 0x74, 0x74, 0x74, 0x74, 0x74, 0x8c, 0xfc, // 79 (0x4f)
0x0c, 0x74, 0x74, 0x0c, 0x7c, 0x7c, 0x7c, 0xfc, // 80 (0x50)
0x8c, 0x74, 0x74, 0x74, 0x74, 0x6c, 0x94, 0xfc, // 81 (0x51)
0x0c, 0x74, 0x74, 0x0c, 0x74, 0x74, 0x74, 0xfc, // 82 (0x52)
0x8c, 0x74, 0x7c, 0x8c, 0xf4, 0x74, 0x8c, 0xfc, // 83 (0x53)
0x04, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, 0xdc, 0xfc, // 84 (0x54)
0x74, 0x74, 0x74, 0x74, 0x74, 0x74, 0x8c, 0xfc, // 85 (0x55)
0x74, 0x74, 0x74, 0x74, 0xac, 0xac, 0xdc, 0xfc, // 86 (0x56)
0x74, 0x74, 0x74, 0x74, 0x54, 0x24, 0x74, 0xfc, // 87 (0x57)
0x74, 0x74, 0xac, 0xdc, 0xac, 0x74, 0x74, 0xfc, // 88 (0x58)
0x74, 0x74, 0xac, 0xdc, 0xdc, 0xdc, 0xdc, 0xfc, // 89 (0x59)
0x04, 0xf4, 0xec, 0xdc, 0xbc, 0x7c, 0x04, 0xfc, // 90 (0x5a)
};
+528
View File
@@ -0,0 +1,528 @@
/* graphics.c
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "graphics.h"
// Uncomment to send printf() et al. to the Becker port
// instead of the lower-right text window.
//
//#define TRACES_TO_BECKER_PORT
static const byte rgbPaletteValues[NUM_COLORS] =
{
#define PALETTE_ELEMENT(name, rgbCode, cmpCode) rgbCode,
#include "palette.h"
#undef PALETTE_ELEMENT
};
static const byte cmpPaletteValues[NUM_COLORS] =
{
#define PALETTE_ELEMENT(name, rgbCode, cmpCode) cmpCode,
#include "palette.h"
#undef PALETTE_ELEMENT
};
// Points to either rgbPaletteValues[] or cmpPaletteValues[].
//
static const byte *currentPaletteValues = rgbPaletteValues;
static const byte colorIndexToByte[NUM_COLORS] =
{
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff
};
static struct
{
byte curRow; // 0..TEXT_SCREEN_HEIGHT-1
byte curCol; // 0..TEXT_SCREEN_WIDTH-1
} textWindow;
// color: Palette index (0..15).
//
void
hcls(byte color)
{
byte b = colorIndexToByte[color];
memset16(GRAPHICS_START, ((word) b << 8) | b, NUM_GRAPHICS_BLOCKS * BLOCK_SIZE / 2);
}
void consoleOutHookGraphics(void);
static void
setPaletteFromCurrentArray(void)
{
memcpy((void *) 0xFFB0, currentPaletteValues, NUM_COLORS);
poke(0xFF9A, currentPaletteValues[PAL_SCREEN_BG]); // border color (0..63)
}
void
setPalette(BOOL monitorIsRGB)
{
currentPaletteValues = (monitorIsRGB ? rgbPaletteValues : cmpPaletteValues);
setPaletteFromCurrentArray();
}
void
alternatePalettes(void)
{
setPalette(currentPaletteValues == cmpPaletteValues);
}
void
showGraphicsMode(void)
{
setPaletteFromCurrentArray();
poke(0xFF90, 0x4C); // reset CoCo 2 compatible bit
poke(0xFF98, 0x80); // graphics mode
poke(0xFF99, 0b00011010); // 256x192, 16 colors
// Tell the GIME chip that the memory at FIRST_GRAPHICS_BLOCK is the screen.
pokeWord(0xFF9D, (word) FIRST_GRAPHICS_BLOCK << 10);
// Redirect printf() et al. to the software text screen.
setConsoleOutHook(consoleOutHookGraphics);
}
void
setupGraphicsMode(void)
{
for (byte i = 0; i < NUM_GRAPHICS_BLOCKS; ++i)
mmuSet(FIRST_GRAPHICS_BANK + i, FIRST_GRAPHICS_BLOCK + i);
hcls(PAL_SCREEN_BG); // empty the screen before showing it
textWindow.curRow = TEXT_WIN_TOP;
textWindow.curCol = TEXT_WIN_LEFT;
}
asm byte *
getPixelAddr(byte x, byte y)
{
#if 0 /* Original C code. */
return (byte *) (GRAPHICS_START + y * (word) BYTES_PER_ROW + (x / 2));
#else
asm
{
; 'x' is in B, as per __gcccall.
lsrb ; x / 2
ldx #GRAPHICS_START
abx
ldb 3,s ; y
lda #BYTES_PER_ROW
mul ; D = y * (word) BYTES_PER_ROW
leax d,x ; add to GRAPHICS_START + x / 2
; Return value left in X as per __gcccall.
}
#endif
}
static const byte sixteenColorModeMasks[2] = { 0b00001111, 0b11110000 };
// Expensive if used to set many pixels.
// Assumes 256x192x16.
//
void
setPixel(byte x, byte y, byte color)
{
byte mask = sixteenColorModeMasks[x & 1]; // the zero bits are where 'color' will go
byte *changedByte = getPixelAddr(x, y);
#if 0 //ndef NDEBUG
if (changedByte < GRAPHICS_START || changedByte >= GRAPHICS_END)
{
printf("!setPixel(%u,%u,%u):%p,%p,%p.", x, y, color, changedByte, GRAPHICS_START, GRAPHICS_END);
for (;;)
;
}
#endif
byte colorByte = (x & 1 ? color : (color << 4));
*changedByte = *changedByte & mask | colorByte;
}
byte
getPixel(byte x, byte y)
{
byte mask = sixteenColorModeMasks[x & 1];
byte *targetByte = getPixelAddr(x, y);
return x & 1 ? *targetByte & 0x0F : (*targetByte >> 4);
}
void
hline(byte left, byte right, byte row, byte colorIndex)
{
const byte oddCol = left & 1;
byte mask = sixteenColorModeMasks[oddCol]; // the zero bits are where 'colorIndex' will go
byte *changedByte = getPixelAddr(left, row);
const byte evenColorByte = colorIndex << 4;
const byte oddColorByte = colorIndex;
const byte colorByteXorValue = oddColorByte ^ evenColorByte;
byte colorByte = (oddCol ? oddColorByte : evenColorByte);
for ( ; left <= right; ++left)
{
*changedByte = *changedByte & mask | colorByte;
if (left & 1) // if just processed odd horiz. coord
++changedByte; // then next pixel is in next byte
mask = ~mask; // alternate between 0xF0 and 0x0F
colorByte ^= colorByteXorValue; // alternate betweenoddColorByte and evenColorByte
}
}
void
vline(byte top, byte bottom, byte column, byte colorIndex)
{
assert(top < SCRN_HEIGHT);
assert(bottom < SCRN_HEIGHT);
assert(colorIndex < NUM_COLORS);
const byte oddCol = column & 1;
const byte mask = sixteenColorModeMasks[oddCol]; // the zero bits are where 'colorIndex' will go
const byte colorByte = (oddCol ? colorIndex : (colorIndex << 4));
byte *changedByte = getPixelAddr(column, top);
for ( ; top <= bottom; ++top, changedByte += BYTES_PER_ROW)
*changedByte = *changedByte & mask | colorByte;
}
void
draw6ByteWideRectangle(byte leftPosInBytes,
byte upperRowInPixels,
byte heightInPixels,
byte colorIndex)
{
byte byteToWrite = colorIndexToByte[colorIndex];
word wordToWrite = ((word) byteToWrite << 8) | byteToWrite;
byte *bytePtr = (byte *) (GRAPHICS_START + upperRowInPixels * (word) BYTES_PER_ROW + leftPosInBytes);
for (byte row = 0; row < heightInPixels; ++row, bytePtr += BYTES_PER_ROW)
{
* (word *) bytePtr = wordToWrite;
* (word *) (bytePtr + 2) = wordToWrite;
* (word *) (bytePtr + 4) = wordToWrite;
}
}
void
drawRect(byte leftPosInPixels,
byte upperRowInPixels,
byte widthInPixels,
byte heightInPixels,
byte colorIndex)
{
byte right = leftPosInPixels + widthInPixels - 1;
for ( ; heightInPixels--; ++upperRowInPixels)
hline(leftPosInPixels, right, upperRowInPixels, colorIndex);
}
void
drawBox(byte leftX, byte topY, byte rightX, byte bottomY, byte colorIndex)
{
hline(leftX, rightX, topY, colorIndex);
hline(leftX, rightX, bottomY, colorIndex);
vline(topY, bottomY, leftX, colorIndex);
vline(topY, bottomY, rightX, colorIndex);
}
// Colors currently used by writeCharEx().
//
static byte foreColorByte = PAL_PROMPTS | (PAL_PROMPTS << 4);
static byte backColorByte = PAL_SCREEN_BG | (PAL_SCREEN_BG << 4);
// Uses foreColorByte and backColorByte.
//
static void
writeCharEx(const byte font[], byte numRows, byte numColumns,
byte x, byte y,
word glyphIndex)
{
const byte *glyph = &font[glyphIndex << 3];
const byte firstMaskInRow = sixteenColorModeMasks[x & 1];
byte *changedByte = getPixelAddr(x, y);
for (byte row = 0; row < numRows; ++row)
{
byte glyphByte = glyph[row];
byte mask = firstMaskInRow; // the zero bits are where the 4-bit pixel will go
byte *firstChangedByteInRow = changedByte;
for (byte col = 0; col < numColumns; ++col, glyphByte <<= 1)
{
byte colorByte = (glyphByte & 0x80) ? backColorByte : foreColorByte; // 2 nybbles set
*changedByte = *changedByte & mask | (colorByte & ~mask);
mask = ~mask; // 11110000 <-> 00001111: next pixel will go in other nybble
if (mask == 0b00001111) // if next pixel will go in high nybble
++changedByte; // next pixel will go in next byte
}
changedByte = firstChangedByteInRow + BYTES_PER_ROW;
}
}
void
writeTileCharAtPixelPosWithColors(byte x, byte y, byte tileType, byte foreColorIndex, byte backColorIndex)
{
byte f = foreColorByte, b = backColorByte;
foreColorByte = foreColorIndex | (foreColorIndex << 4);
backColorByte = backColorIndex | (backColorIndex << 4);
writeCharEx((const byte *) FONT_5x8_BUFFER, 7, 5, x, y, tileType - 1);
foreColorByte = f;
backColorByte = b;
}
void
writeCharAtPixelPos(byte x, byte y, char asciiCode)
{
writeCharEx((const byte *) FONT_4x8_BUFFER, CHAR_HEIGHT, CHAR_WIDTH - 1,
x, y, (byte) asciiCode - 32);
}
void
writeStringAt(byte textCol, byte textRow, const char *str)
{
byte startCol = textCol;
for ( ; *str; ++str)
{
if (*str == '\n')
{
textCol = startCol;
++textRow;
}
else
writeCharAt(textCol++, textRow, *str);
}
}
void
writeDecimalAt(byte textCol, byte textRow, unsigned value)
{
char str[6];
utoa10(value, str);
writeStringAt(textCol, textRow, str);
}
#ifndef TRACES_TO_BECKER_PORT
// N.B.: Assumes that the text window is at the right of the screen.
//
static void
scrollTextWindowUp(void)
{
byte homeX = TEXT_WIN_LEFT * CHAR_WIDTH; // in pixels
byte *p = getPixelAddr(homeX, TEXT_WIN_TOP * CHAR_HEIGHT);
byte numBytesToCopyPerRow = (byte) (256 - homeX) / 2; // assumes homeX > 0 and that text win at right of scrn
byte y;
for (y = TEXT_WIN_TOP * CHAR_HEIGHT; y < SCRN_HEIGHT - CHAR_HEIGHT; ++y, p += BYTES_PER_ROW)
{
byte *dest = p;
if (homeX & 1) // if left-most byte of text window is not fully part of text window
{
dest[0] = (dest[0] & 0b11110000) | (dest[BYTES_PER_ROW * (word) CHAR_HEIGHT] & 0b00001111);
++dest; // move on to next byte
}
memcpy(dest, dest + (BYTES_PER_ROW * (word) CHAR_HEIGHT), numBytesToCopyPerRow);
}
byte colorByte = (PAL_SCREEN_BG << 4) | PAL_SCREEN_BG;
for ( ; y < SCRN_HEIGHT; ++y, p += BYTES_PER_ROW) // clear bottom
{
byte *dest = p;
if (homeX & 1)
{
dest[0] = (dest[0] & 0b11110000) | PAL_SCREEN_BG;
++dest; // move on to next byte
}
memset(dest, colorByte, numBytesToCopyPerRow);
}
}
#endif /* TRACES_TO_BECKER_PORT */
// Called by printf() and putchar() when in graphics mode.
// The character to be printed is in register A.
// Must preserve B and X.
//
void
consoleOutHookGraphics(void)
{
#ifdef TRACES_TO_BECKER_PORT
asm
{
sta $FF42
}
#else
char ch;
asm
{
pshs x,b ; must be preserved
sta :ch ; character to write
}
byte goToNewLine = FALSE;
switch (ch)
{
case '\r':
// Write spaces until current line filled.
for (byte col = textWindow.curCol; col < TEXT_WIN_LEFT + TEXT_WIN_WIDTH; ++col)
writeCharAt(col, textWindow.curRow, ' ');
goToNewLine = TRUE;
break;
default:
if ((byte) ch >= ' ' && (byte) ch <= 127) // DEL rendered as filled rectangle
{
writeCharAt(textWindow.curCol, textWindow.curRow, ch);
if (++textWindow.curCol == TEXT_WIN_LEFT + TEXT_WIN_WIDTH) // if end of row reached
goToNewLine = TRUE;
}
}
if (goToNewLine)
{
textWindow.curCol = TEXT_WIN_LEFT;
if (textWindow.curRow < (byte) (TEXT_WIN_TOP + TEXT_WIN_HEIGHT - 1)) // if not on last row
++textWindow.curRow;
else
scrollTextWindowUp();
}
asm
{
puls b,x
}
#endif
}
void
getCurrentTextWindowPos(byte *textCol, byte *textRow)
{
*textCol = textWindow.curCol;
*textRow = textWindow.curRow;
}
static byte *hardwareTextCursor = (byte *) HW_TEXT_SCREEN_BUFFER;
// Called by printf() and putchar() when in hardware text mode.
// The character to be printed is in register A.
// Must preserve B and X.
//
// Does NOT support scrolling. The cursor must not go beyond last row.
//
static asm __norts__ void
hardwareTextScreenConsoleOut(void)
{
asm
{
pshs x,b
ldx :hardwareTextCursor
cmpa #13
beq @cr
sta ,x+
bra @done
@cr
; Begin hardwareTextCursor back to start of current row, then to start of next row.
ldd #-HW_TEXT_SCREEN_BUFFER
leax d,x ; X now offset from HW_TEXT_SCREEN_BUFFER
; Divide X by 40 by subtraction, to get the remainder (0..39)
bra @divBy40Cond
@divBy40Loop
leax -HW_TEXT_SCREEN_WIDTH,x
@divBy40Cond
cmpx #HW_TEXT_SCREEN_WIDTH
bhs @divBy40Loop ; loop if still not in first row
;
tfr x,d ; get remainder (column number) in B
negb ; negate column number
ldx :hardwareTextCursor
leax b,x ; put cursor back at start of row (signed operation)
leax HW_TEXT_SCREEN_WIDTH,x ; put cursor at start of next row
@done
stx :hardwareTextCursor
@ret
puls b,x,pc
}
}
void
showHardwareTextScreen(void)
{
// Set CoCo 3 hi res text mode.
// Must be consistent with HW_TEXT_SCREEN_WIDTH, HW_TEXT_SCREEN_HEIGHT, HW_TEXT_SCREEN_BUFFER.
//
* (byte *) 0xFF90 = 0x4C; // reset CoCo 2 compatible bit
* (byte *) 0xFF98 = 0x03; // text mode
* (byte *) 0xFF99 = 0b00000100; // 192 lines per field, 40x24 grid, NO color attributes
* (byte *) 0xFF9A = currentPaletteValues[PAL_SCREEN_BG];
* (unsigned *) 0xFF9D = 0xFC00; // specifies $7E000 as base address; mapped to HW_TEXT_SCREEN_BUFFER
// Set the foreground and background colors through palette slots 1 and 0.
//
* (byte *) 0xFFB0 = currentPaletteValues[PAL_SCREEN_BG];
* (byte *) 0xFFB1 = currentPaletteValues[PAL_PROMPTS];
setConsoleOutHook(hardwareTextScreenConsoleOut);
}
void
clearHardwareTextScreen(void)
{
memset16((void *) HW_TEXT_SCREEN_BUFFER, 0x2020, HW_TEXT_SCREEN_WIDTH * HW_TEXT_SCREEN_HEIGHT / 2);
hardwareTextCursor = (byte *) HW_TEXT_SCREEN_BUFFER;
}
+154
View File
@@ -0,0 +1,154 @@
/* graphics.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _H_graphics
#define _H_graphics
#include "defs.h"
// Define names for the palette slots, e.g., PAL_SCREEN_BG for
// the screen background color.
//
enum
{
#define PALETTE_ELEMENT(name, rgbCode, cmpCode) CONCAT(PAL_, name),
#include "palette.h"
#undef PALETTE_ELEMENT
};
// Displays the 40x24 no-color text screen.
// Redirects printf() et al. to it.
// Scrolling is not supported. The cursor must not go beyond the last row.
// Call showGraphicsMode() to go to the graphics screen.
//
void showHardwareTextScreen(void);
// Also homes the cursor.
//
void clearHardwareTextScreen(void);
void hcls(byte color);
// Sets MMU pages to point to the graphics blocks.
// Clears the graphics screen.
// Homes the cursor used by printf() et al., which get redirected
// to a part of the graphics screen.
//
void setupGraphicsMode();
// Initializes the 16 palette slots according to monitorIsRGB.
// If it is false, a composite monitor is assumed.
// If this function is never called, the default palette is RGB.
//
void setPalette(BOOL monitorIsRGB);
// Switches between the RGB and CMP palettes.
//
void alternatePalettes(void);
// Shows the graphics mode that was set up by setupGraphicsMode(),
// which must have been called before this function can be called.
// Redirects printf() et al. to a part of the graphics screen.
// Does not move the cursor.
//
void showGraphicsMode(void);
// Returns the address of the byte that contains the pixel at (x, y).
// x, y: Positions in pixels.
//
__gcccall byte *getPixelAddr(byte x, byte y);
void setPixel(byte x, byte y, byte color);
byte getPixel(byte x, byte y);
void hline(byte left, byte right, byte row, byte colorIndex);
void vline(byte top, byte bottom, byte column, byte colorIndex);
void draw6ByteWideRectangle(byte leftPosInBytes,
byte upperRowInPixels,
byte heightInPixels,
byte colorIndex);
// Draws a full rectangle.
//
void drawRect(byte leftPosInPixels,
byte upperRowInPixels,
byte widthInPixels,
byte heightInPixels,
byte colorIndex);
// Draws an empty box.
// N.B.: rightX and bottomY are positions, not dimensions.
//
void drawBox(byte leftX, byte topY, byte rightX, byte bottomY, byte colorIndex);
// Writes a character in a 4x8 font at a pixel-precise position.
// x: 0..251.
// y: 0..184.
// asciiCode: 0..127.
//
void writeCharAtPixelPos(byte x, byte y, char asciiCode);
// Writes a character in a 4x8 font at a text grid position.
// textCol: 0..50.
// textRow: 0..23.
// asciiCode: 0..127.
//
#define writeCharAt(textCol, textRow, asciiCode) (writeCharAtPixelPos((textCol) * CHAR_WIDTH, (textRow) * CHAR_HEIGHT, (asciiCode)))
// The text must not go beyond the row it starts on.
// '\n' goes to the next line. The text must not go below
// the bottom of the text window.
//
void writeStringAt(byte textCol, byte textRow, const char *str);
void writeDecimalAt(byte textCol, byte textRow, unsigned value);
// Returns a position in a 51x24 grid.
//
void getCurrentTextWindowPos(byte *textCol, byte *textRow);
// Writes a capital letter in a tile-specific font.
// tileType: 1..26.
//
void writeTileCharAtPixelPosWithColors(byte x, byte y, byte tileType, byte foreColorIndex, byte backColorIndex);
#endif /* _H_graphics */
+2084
View File
File diff suppressed because it is too large. Load diff
+35
View File
@@ -0,0 +1,35 @@
/* palette.h
Copyright (C) 2026 Pierre Sarrazin <http://sarrazip.com/>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Monitor type: RGB CMP
//
PALETTE_ELEMENT(SCREEN_BG, 3, 13)
PALETTE_ELEMENT(BOARD_BG, 56, 32)
PALETTE_ELEMENT(BOARD_GRID, 63, 48) /* lines around the squares */
PALETTE_ELEMENT(TRIPLE_WORD, 38, 22)
PALETTE_ELEMENT(DOUBLE_WORD, 60, 38)
PALETTE_ELEMENT(TRIPLE_LETTER, 9, 11)
PALETTE_ELEMENT(DOUBLE_LETTER, 59, 60)
PALETTE_ELEMENT(BOARD_WRITING, 0, 0) /* board and tiles */
PALETTE_ELEMENT(TILE_BG, 62, 53)
PALETTE_ELEMENT(PROMPTS, 54, 35) /* 51x24 writing at right of board */
PALETTE_ELEMENT(WORD_ENTRY_CURSOR, 17, 17)
PALETTE_ELEMENT(FREE11, 12, 11) /* the free CMP values have not been used or tested */
PALETTE_ELEMENT(FREE12, 24, 30)
PALETTE_ELEMENT(FREE13, 34, 21)
PALETTE_ELEMENT(FREE14, 47, 56)
PALETTE_ELEMENT(FREE15, 55, 52)
+13597
View File
File diff suppressed because it is too large. Load diff