22 Commits

Author SHA1 Message Date
sucupira 84c0363067 fix(app): revelation reel+distance jamais dessinee (effet Svelte sans dependance)
Au montage, l'effet $effect de revelation retournait avant toute lecture
reactive (carte pas encore creee) : Svelte n'enregistrait aucune dependance
et ne le relancait jamais — ni le marqueur reel, ni la ligne, ni l'etiquette
de distance n'apparaissaient apres validation.

- lecture inconditionnelle de real en tete d'effet
- garde isStyleLoaded() au lieu de loaded() (faux pendant le chargement
  des tuiles, typique juste apres un pan/zoom pour placer son guess)

Verifie au navigateur (Playwright) : 2 marqueurs apres validation, ligne
pointillee + etiquette de distance, nettoyage au round suivant, repetition OK.
2026-07-19 20:31:20 -04:00
sucupira 70f448a4f7 chore: ignore jwe_ynh/ (depot separe) 2026-07-19 19:59:35 -04:00
sucupira 79b2ef72a9 docs: ADR-003 mode street Mapillary (architecture), README 5 modes, deploiement token PUBLIC_MAPILLARY_TOKEN 2026-07-18 20:15:13 -04:00
sucupira e4a0bfd045 feat(app): mode street 'An lari a' - visionneuse mapillary-js lazy, /api/round?mode=street, i18n FR/GCF (ADR-003) 2026-07-18 20:15:03 -04:00
sucupira fab020ba75 verify: scripts curation + validation corpus street (fetch reel Mapillary/geo.api/Wikidata, retry 429) 2026-07-18 20:14:52 -04:00
sucupira 2e6f7e8830 contenu: corpus street 20 lieux (5/region) - images Mapillary CC BY-SA, verite figee, QID communes, credits 2026-07-18 20:14:52 -04:00
sucupira 19b83159a9 fix(resultat): le marqueur du joueur reste visible, marqueur reel + ligne + etiquette distance + fitBounds (comparaison visuelle facon GeoGuessr) 2026-07-16 23:45:17 -04:00
sucupira 2f8867497a docs: readme sans reference au dossier prompts 2026-07-16 23:26:44 -04:00
sucupira c5e925b3c4 chore: suppression du dossier prompts (specs de mission, archivees hors depot) 2026-07-16 23:26:13 -04:00
sucupira 223511f718 docs: architecture section phase 2, audit passe2 - R1/R2 soldees 2026-07-16 23:21:31 -04:00
sucupira ce04a56f1e feat(carte): carte SVG legere des 4 regions sur accueil et bilans defi (ADR-002, 92 KB gz, SSR sans MapLibre) 2026-07-16 23:21:31 -04:00
sucupira 3f4f284c0a feat(defi): lien a seed /defi/[seed] - memes 5 lieux pour tous, PRNG seede serveur deterministe (ADR-001 v1) 2026-07-16 23:21:31 -04:00
sucupira 8178e87f87 docs: rapport d'audit passe 2 (0 FAIL restant), architecture mise a jour, prompts de mission 2026-07-16 21:58:32 -04:00
sucupira 0b01013411 verify: script de validation du corpus (C1 QIDs, C2 vrais nulls, C3 coords, C4c licences) 2026-07-16 21:58:32 -04:00
sucupira d52034712d fix(app): proxy photo opaque + EXIF strip + WebP (C4), radius_eff communes immenses (A1), variante no-frwiki (A3), cache wiki 24h 2026-07-16 21:58:32 -04:00
sucupira e41a508d77 fix(contenu): Savane des Petrifications -> Q3474455 (C2), nouvelle lacune Anse Grosse Roche, aires communales geo.api.gouv.fr (A1) 2026-07-16 21:58:32 -04:00
sucupira 441b27d92b chore: suppression de la v1 PHP (disponible dans l'historique), licence racine MIT, README v2 2026-07-16 21:19:00 -04:00
sucupira d9b07d6729 readme: section JWE v2 2026-07-16 21:05:22 -04:00
sucupira f5312bb3b9 docs: audit OKI - conforme, fix anti-spoiler credit photo 2026-07-16 21:05:22 -04:00
sucupira 923fa2869f app: refonte JWE v2 - SvelteKit 2 + Svelte 5 + MapLibre, 4 modes de jeu, API anti-triche, ecran Cas B 'Pwen blinde', i18n FR/GCF, PWA 2026-07-16 21:05:22 -04:00
sucupira ee85a10e20 contenu: corpus de 40 lieux verifies (Wikidata + photos Commons CC), 9 lieux sans page Wikipedia (lacune documentaire) 2026-07-16 21:05:22 -04:00
sucupira 8a9bec0143 docs: mission, decisions d'architecture, guides de deploiement et contribution 2026-07-16 21:05:22 -04:00
88 changed files with 17268 additions and 1868 deletions
+2
View File
@@ -0,0 +1,2 @@
# Paquet YunoHost (dépôt séparé : ORGANISATION-KA-INTERNATIONALE/jwe_ynh)
jwe_ynh/
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.2 MiB

+28 -661
View File
@@ -1,661 +1,28 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<http://www.gnu.org/licenses/>.
MIT License
Copyright (c) 2026 ORGANISATION KA INTERNATIONALE (OKI) & contributeurs JWE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Note : les photographies affichées par l'application restent la propriété de
leurs auteurs respectifs et sont distribuées sous leurs licences Wikimedia
Commons (voir content/credits.md). Les extraits d'articles Wikipédia sont
sous licence CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/deed.fr).
+23 -42
View File
@@ -1,14 +1,10 @@
# JWE
<p align="center">
Ce projet cartographique est une application Web simple qui vous permet de tester vos connaissances des communes ou des pays proposés à l'aide de cartes interactives.
JWE est un jeu de géolocalisation souverain, dans l'esprit de GeoGuessr, centré sur 4 régions : <strong>Guadeloupe, Martinique, Guyane, La Réunion</strong>. Le joueur voit une photo unique d'un lieu — ou navigue dans une rue en visionneuse Mapillary (mode <em>An lari a</em>) — et place un marqueur sur une carte pour deviner la commune — puis découvre une fiche éducative Wikipédia/Wikidata… ou un appel à contribution quand le lieu n'y est pas documenté (<em>Pwen blindé</em>).
</p>
<p align="center">
Il ne nécessite qu'un serveur Web local pour fonctionner, tel que Nginx, Apache, ou un serveur PHP intégré.
</p>
<p align="center">
<a href="https://liberapay.com/OKI/donate/">
<img src="https://img.shields.io/liberapay/receives/OKI.svg?logo=liberapay">
<img src="https://img.shields.io/liberapay/patrons/OKI.svg?logo=liberapay">
@@ -16,55 +12,40 @@ Il ne nécessite qu'un serveur Web local pour fonctionner, tel que Nginx, Apache
</a>
</p>
<p align="center">
<img src="https://codeberg.org/OKI/jwe/raw/commit/166b356d21e4b3271afd3be111eae57e6bee7a95/972.gif" />
</p>
- **Souverain** : zéro Google, zéro Mapbox. MapLibre + tiles libres, Wikipédia/Wikidata, auto-hébergeable sur un petit VPS. (Exception documentée : le mode street « An lari a » utilise la visionneuse Mapillary — images CC BY-SA 4.0, lib MIT, token client gratuit.)
- **Éthique** : pas de comptes, pas de leaderboard, pas de mécanique dopaminergique.
- **Bilingue** : français / créole.
- **5 modes** : Konnèt moniman, Kote mwen ye ?, Défi 5 rounds, Aprann (explorer), An lari a (street-level Mapillary).
- **Stack** : Svelte 5 + SvelteKit 2, MapLibre GL JS, mapillary-js, Node ≥ 20, licence MIT.
## Utilisation
1. **Clonage du dépôt**
Clonez ce dépôt sur votre ordinateur en utilisant la commande suivante :
```bash
git clone https://codeberg.org/OKI/jwe.git
```
2. **Configuration du Serveur Web Local**
Placez le répertoire cloné dans le répertoire racine de votre serveur Web local. Vous pouvez également exécuter la commande suivante depuis le répertoire du projet :
```bash
php -S 127.0.0.1:8000
git clone https://labola.o-k-i.net/ORGANISATION-KA-INTERNATIONALE/JWE.git
cd JWE/app
npm ci
cp .env.example .env # puis renseignez PUBLIC_MAPILLARY_TOKEN (token client gratuit)
npm run dev # développement
npm run build && node build # production (adapter-node)
```
3. **Accès à l'Application**
## Documentation
Accédez à l'application via votre navigateur Web en utilisant l'adresse `http://127.0.0.1:8000`.
- [`docs/architecture.md`](docs/architecture.md) — décisions d'architecture (ADR).
- [`docs/deploiement.md`](docs/deploiement.md) — auto-hébergement (SvelteKit + tileserver-gl).
- [`docs/contribution.md`](docs/contribution.md) — ajouter un lieu et lier sa fiche Wikidata.
- [`docs/audit-oki.md`](docs/audit-oki.md) — audit qualité et doctrine OKI.
## Contributions
Les contributions sont les bienvenues ! Si vous souhaitez contribuer à ce projet, n'hésitez pas à soumettre des pull requests.
Les contributions sont les bienvenues ! Ajouter un lieu se fait par pull request (voir [`docs/contribution.md`](docs/contribution.md)).
## License
## Historique
Copyright (C) 2024 Cédric Famibelle-Pronzola & ORGANISATION KA INTERNATIONALE (OKI)
La version 1 (PHP, cartes des communes) a été remplacée par cette refonte en juillet 2026 ; elle reste disponible dans l'historique Git (`git log` avant le commit de refonte).
## Licence
### FR
Copyright (C) 2024-2026 Cédric Famibelle-Pronzola & ORGANISATION KA INTERNATIONALE (OKI)
Ce programme est un logiciel libre : vous pouvez le redistribuer et/ou le modifier selon les termes de la licence publique générale GNU Affero publiée par la Free Software Foundation, soit la version 3 de la licence, soit (à votre choix) toute version ultérieure.
Ce programme est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE GARANTIE ; sans même la garantie implicite de COMMERCIALISATION ou d'ADAPTATION À UN USAGE PARTICULIER. Voir la licence publique générale GNU Affero pour plus de détails.
Vous devriez avoir reçu une copie de la licence publique générale GNU Affero avec ce programme. Si ce n'est pas le cas, consultez https://www.gnu.org/licenses/.
### EN
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License along with this program. If not, see https://www.gnu.org/licenses/.
Code sous licence **MIT** (voir [LICENSE](LICENSE)). Les photographies restent la propriété de leurs auteurs sous leurs licences Wikimedia Commons ; les images street-level Mapillary sont sous CC BY-SA 4.0 par leurs contributeurs (voir [`content/credits.md`](content/credits.md)) ; les extraits Wikipédia sont sous CC BY-SA 4.0.
+7
View File
@@ -0,0 +1,7 @@
# Token client Mapillary (gratuit) : https://www.mapillary.com/dashboard/developers
# Requis uniquement pour le mode street « An lari a » (visionneuse mapillary-js).
# Token client : conçu pour être exposé côté navigateur (rate-limité par app).
PUBLIC_MAPILLARY_TOKEN=
# Optionnel : URL d'un style/tiles auto-hébergé (tileserver-gl) — voir docs/deploiement.md
# PUBLIC_TILES_URL=
+7
View File
@@ -0,0 +1,7 @@
node_modules
build
.svelte-kit
.env
.env.*
!.env.example
.vite
+28
View File
@@ -0,0 +1,28 @@
MIT License
Copyright (c) 2026 ORGANISATION KA INTERNATIONALE (OKI) & contributeurs JWE
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
---
Note : les photographies affichées par l'application restent la propriété de
leurs auteurs respectifs et sont distribuées sous leurs licences Wikimedia
Commons (voir content/credits.md). Les extraits d'articles Wikipédia sont
sous licence CC BY-SA 4.0 (https://creativecommons.org/licenses/by-sa/4.0/deed.fr).
+5892
View File
File diff suppressed because it is too large Load Diff
+29
View File
@@ -0,0 +1,29 @@
{
"name": "jwe",
"version": "2.0.1",
"private": true,
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"start": "node build",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json"
},
"devDependencies": {
"@sveltejs/adapter-node": "^5.2.0",
"@sveltejs/kit": "^2.16.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@types/node": "^26.1.1",
"mapshaper": "^0.7.45",
"svelte": "^5.0.0",
"svelte-check": "^4.1.0",
"typescript": "^5.6.0",
"vite": "^6.0.0"
},
"dependencies": {
"mapillary-js": "^4.1.2",
"maplibre-gl": "^5.1.0",
"sharp": "^0.35.3"
}
}
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env node
/**
* Génère `src/lib/map/regions-geo.json` : contours simplifiés des communes des
* 4 régions JWE, pour la carte SVG statique des écrans hors-jeu (ADR-002).
*
* Pipeline : geo.api.gouv.fr (contours communes, gratuit, sans clé)
* → simplification mapshaper (Visvalingam, `keep-shapes`)
* → anneaux externes uniquement, MultiPolygons aplatis, coords à 5 décimales
* → JSON minifié versionné dans le repo.
*
* Rejouable : `node scripts/build-carte-regions.mjs [pourcentage]`
* pourcentage = seuil mapshaper (défaut 7%, calibré : ~90 KB gzip -9).
* Le script affiche le poids brut et gzip -9 (budget ADR-002 V1 : ≤ 150 KB gzippé).
*/
import { writeFile } from 'node:fs/promises';
import { gzipSync } from 'node:zlib';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import mapshaper from 'mapshaper';
const REGIONS = {
'01': { cle: 'GUADELOUPE', nom: 'Guadeloupe', creole: 'Gwadloup' },
'02': { cle: 'MARTINIQUE', nom: 'Martinique', creole: 'Matinik' },
'03': { cle: 'GUYANE', nom: 'Guyane', creole: 'Giyan' },
'04': { cle: 'REUNION', nom: 'La Réunion', creole: 'Léryinyon' }
};
const USER_AGENT = 'JWE-OKI/2.0 (https://labola.o-k-i.net ; scripts/build-carte-regions)';
const BUDGET_GZ = 150 * 1024;
const SORTIE = path.join(
path.dirname(fileURLToPath(import.meta.url)),
'..',
'src',
'lib',
'map',
'regions-geo.json'
);
const pourcentage = process.argv[2] ?? '7%';
async function fetchCommunes(codeRegion) {
const url = `https://geo.api.gouv.fr/communes?codeRegion=${codeRegion}&fields=nom,code,contour&format=json&geometry=contour`;
const res = await fetch(url, {
headers: { 'User-Agent': USER_AGENT, Accept: 'application/json' }
});
if (!res.ok) throw new Error(`geo.api.gouv.fr région ${codeRegion} : HTTP ${res.status}`);
return res.json();
}
function applyCommands(cmd, inputs) {
return new Promise((resolve, reject) => {
mapshaper.applyCommands(cmd, inputs, (err, out) => (err ? reject(err) : resolve(out)));
});
}
/** Simplifie un GeoJSON avec mapshaper et renvoie le GeoJSON parsé. */
async function simplifier(featureCollection) {
const cmd = `-i communes.geojson -simplify ${pourcentage} keep-shapes -o sortie.geojson`;
const out = await applyCommands(cmd, { 'communes.geojson': featureCollection });
const brut = out['sortie.geojson'];
// mapshaper renvoie un Buffer en sortie fichier (Node), une string ou un objet selon le format
if (Buffer.isBuffer(brut)) return JSON.parse(brut.toString('utf8'));
return typeof brut === 'string' ? JSON.parse(brut) : brut;
}
const r5 = (n) => Math.round(n * 1e5) / 1e5;
/** Anneaux externes seuls ; MultiPolygon → plusieurs polygones ; coords arrondies. */
function extrairePolygones(geojson) {
const polygons = [];
for (const feature of geojson.features) {
const g = feature.geometry;
const multi = g?.type === 'MultiPolygon' ? g.coordinates : g?.type === 'Polygon' ? [g.coordinates] : [];
for (const poly of multi) {
const anneau = poly[0];
if (!Array.isArray(anneau) || anneau.length < 4) continue;
polygons.push(anneau.map(([lon, lat]) => [r5(lon), r5(lat)]));
}
}
return polygons;
}
const resultat = {};
for (const [codeRegion, info] of Object.entries(REGIONS)) {
const communes = await fetchCommunes(codeRegion);
const fc = {
type: 'FeatureCollection',
features: communes
.filter((c) => c.contour)
.map((c) => ({
type: 'Feature',
properties: { code: c.code, nom: c.nom },
geometry: c.contour
}))
};
const simplifie = await simplifier(fc);
const polygons = extrairePolygones(simplifie);
const points = polygons.reduce((s, p) => s + p.length, 0);
resultat[info.cle] = { nom: info.nom, creole: info.creole, polygons };
console.log(
`${info.cle.padEnd(11)} ${String(fc.features.length).padStart(3)} communes → ` +
`${String(polygons.length).padStart(3)} polygones, ${points} points`
);
}
const json = JSON.stringify(resultat);
await writeFile(SORTIE, json + '\n', 'utf8');
const brut = Buffer.byteLength(json, 'utf8');
const gz = gzipSync(json, { level: 9 }).length;
console.log(`\n${path.relative(process.cwd(), SORTIE)}`);
console.log(`Brut : ${(brut / 1024).toFixed(1)} KB`);
console.log(`gzip -9 : ${(gz / 1024).toFixed(1)} KB (budget V1 : 150 KB)`);
if (gz > BUDGET_GZ) {
console.error('DÉPASSEMENT DU BUDGET — relancer avec un pourcentage plus faible.');
process.exitCode = 1;
}
+202
View File
@@ -0,0 +1,202 @@
#!/usr/bin/env node
/**
* Curation du corpus street (« An lari a ») — mode Mapillary.
* « Fetch, pas recall » : pour chaque commune cible, interroge l'API Mapillary
* (bbox autour du centre communal, préférence 360° + qualité + récence),
* geo.api.gouv.fr (centre, superficie), api-adresse (nom de rue) et Wikidata
* (QID de la commune via le sitelink frwiki).
*
* Usage : MAPILLARY_TOKEN=… node scripts/curate-street.mjs
* (le token est aussi lu depuis .env : MAPILLARY_TOKEN ou PUBLIC_MAPILLARY_TOKEN)
* Écrit src/lib/server/data/street.json.
*/
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
function chargeEnv() {
try {
for (const ligne of readFileSync(join(ROOT, '.env'), 'utf8').split('\n')) {
const m = ligne.match(/^\s*([A-Z_]+)\s*=\s*(.+?)\s*$/);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
} catch {
/* pas de .env */
}
}
chargeEnv();
const TOKEN = process.env.MAPILLARY_TOKEN || process.env.PUBLIC_MAPILLARY_TOKEN;
if (!TOKEN) {
console.error('Token Mapillary manquant (MAPILLARY_TOKEN ou PUBLIC_MAPILLARY_TOKEN).');
process.exit(1);
}
const UA = { 'User-Agent': 'JWE-OKI/2.0 (curation corpus street; contact: o-k-i.net)' };
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const getJSON = async (url, headers = UA) => {
const res = await fetch(url, { headers });
if (!res.ok) throw new Error(`HTTP ${res.status} sur ${url}`);
return res.json();
};
// Communes cibles : 5 par région, difficulté = précision exigée (pas de FACILE :
// rayon 50 km = trivial en mode street). titreWiki = titre frwiki exact (désambiguïsé).
const SPOTS = [
// — Guadeloupe (971) —
{ region: 'GUADELOUPE', commune: 'Pointe-à-Pitre', titreWiki: 'Pointe-à-Pitre', difficulte: 'MOYEN', indice1: 'Île papillon, aile droite', indice2: 'Port de commerce principal de larchipel' },
{ region: 'GUADELOUPE', commune: 'Les Abymes', titreWiki: 'Les Abymes', difficulte: 'MOYEN', indice1: 'Île papillon, aile droite', indice2: 'Commune la plus peuplée de larchipel' },
{ region: 'GUADELOUPE', commune: 'Le Gosier', titreWiki: 'Le Gosier', difficulte: 'DIFFICILE', indice1: 'Île papillon, aile droite', indice2: 'Station balnéaire au sud de la Grande-Terre' },
{ region: 'GUADELOUPE', commune: 'Sainte-Anne', titreWiki: 'Sainte-Anne (Guadeloupe)', difficulte: 'DIFFICILE', indice1: 'Île papillon, aile droite', indice2: 'Plages au sud de la Grande-Terre' },
{ region: 'GUADELOUPE', commune: 'Basse-Terre', titreWiki: 'Basse-Terre', difficulte: 'EXPERT', indice1: 'Île papillon, aile gauche', indice2: 'Chef-lieu au pied du volcan' },
// — Martinique (972) —
{ region: 'MARTINIQUE', commune: 'Fort-de-France', titreWiki: 'Fort-de-France', difficulte: 'MOYEN', indice1: 'Île aux fleurs', indice2: 'Chef-lieu, sur une grande baie' },
{ region: 'MARTINIQUE', commune: 'Le Lamentin', titreWiki: 'Le Lamentin', difficulte: 'MOYEN', indice1: 'Île aux fleurs', indice2: 'Banlieue du chef-lieu, zone aéroportuaire' },
{ region: 'MARTINIQUE', commune: 'Saint-Pierre', titreWiki: 'Saint-Pierre (Martinique)', difficulte: 'DIFFICILE', indice1: 'Île aux fleurs, côte caraïbe nord', indice2: 'Ville détruite par une éruption en 1902' },
{ region: 'MARTINIQUE', commune: 'Le François', titreWiki: 'Le François', difficulte: 'DIFFICILE', indice1: 'Île aux fleurs, côte atlantique', indice2: 'Bourg face aux îlets du sud' },
{ region: 'MARTINIQUE', commune: 'Sainte-Marie', titreWiki: 'Sainte-Marie (Martinique)', difficulte: 'EXPERT', indice1: 'Île aux fleurs, côte atlantique nord', indice2: 'Musée de la banane et rhum' },
// — Guyane (973) —
{ region: 'GUYANE', commune: 'Cayenne', titreWiki: 'Cayenne', difficulte: 'MOYEN', indice1: 'Terre de forêt amazonienne', indice2: 'Chef-lieu, sur l’île du même nom' },
{ region: 'GUYANE', commune: 'Kourou', titreWiki: 'Kourou', difficulte: 'DIFFICILE', indice1: 'Terre de forêt amazonienne', indice2: 'Ville des fusées' },
{ region: 'GUYANE', commune: 'Saint-Laurent-du-Maroni', titreWiki: 'Saint-Laurent-du-Maroni', difficulte: 'DIFFICILE', indice1: 'Terre de forêt amazonienne, à louest', indice2: 'Ville du fleuve Maroni, ancien bagne' },
{ region: 'GUYANE', commune: 'Matoury', titreWiki: 'Matoury', difficulte: 'EXPERT', indice1: 'Terre de forêt amazonienne', indice2: 'Banlieue sud du chef-lieu' },
{ region: 'GUYANE', commune: 'Remire-Montjoly', titreWiki: 'Remire-Montjoly', difficulte: 'EXPERT', indice1: 'Terre de forêt amazonienne', indice2: 'Plages à lest du chef-lieu' },
// — La Réunion (974) —
{ region: 'REUNION', commune: 'Saint-Denis', titreWiki: 'Saint-Denis (La Réunion)', difficulte: 'MOYEN', indice1: 'Île intense de locéan Indien', indice2: 'Chef-lieu, au nord' },
{ region: 'REUNION', commune: 'Saint-Pierre', titreWiki: 'Saint-Pierre (La Réunion)', difficulte: 'MOYEN', indice1: 'Île intense de locéan Indien', indice2: 'Capitale du sud, front de mer animé' },
{ region: 'REUNION', commune: 'Le Tampon', titreWiki: 'Le Tampon', difficulte: 'DIFFICILE', indice1: 'Île intense de locéan Indien', indice2: 'Commune des hauts, dans le sud' },
{ region: 'REUNION', commune: 'Saint-Paul', titreWiki: 'Saint-Paul (La Réunion)', difficulte: 'DIFFICILE', indice1: 'Île intense de locéan Indien', indice2: 'Côte ouest, premier site de peuplement' },
{ region: 'REUNION', commune: 'Saint-André', titreWiki: 'Saint-André (La Réunion)', difficulte: 'EXPERT', indice1: 'Île intense de locéan Indien', indice2: 'Côte est, pays de la canne' }
];
const PREFIXE_REGION = { GUADELOUPE: '971', MARTINIQUE: '972', GUYANE: '973', REUNION: '974' };
async function centreCommune(spot) {
const data = await getJSON(
`https://geo.api.gouv.fr/communes?nom=${encodeURIComponent(spot.commune)}&codeDepartement=${PREFIXE_REGION[spot.region]}&fields=centre,surface,code,mairie&limit=8`
);
const c = data[0];
if (!c) throw new Error(`commune introuvable sur geo.api.gouv.fr`);
// La mairie est un meilleur ancrage que le centroïde (les communes DOM
// englobent des reliefs : le centroïde tombe souvent hors du centre-ville).
const p = c.mairie?.coordinates ? c.mairie.coordinates : c.centre.coordinates;
return { lat: p[1], lon: p[0], surfaceHa: c.surface };
}
async function chercherImage(lat, lon) {
const champs = 'id,is_pano,captured_at,computed_geometry,geometry,creator,quality_score';
const note = (img) => (img.quality_score ?? 0.5) * 1e13 + (img.captured_at ?? 0);
// 1) bbox autour de l'ancre (< 0,01° de côté, contrainte API), pano d'abord
const demi = 0.0045;
const bbox = `${lon - demi},${lat - demi},${lon + demi},${lat + demi}`;
for (const pano of ['&is_pano=true', '']) {
const data = await getJSON(
`https://graph.mapillary.com/images?access_token=${encodeURIComponent(TOKEN)}&fields=${champs}&bbox=${bbox}&limit=200${pano}`
);
if (data.data?.length) {
const triees = [...data.data].sort((a, b) => note(b) - note(a));
return { image: triees[0], total: data.data.length };
}
}
// 2) grille de recherches par rayon (50 m) autour de l'ancre
const parId = new Map();
for (const dLat of [-0.004, 0, 0.004]) {
for (const dLon of [-0.004, 0, 0.004]) {
try {
const data = await getJSON(
`https://graph.mapillary.com/images?access_token=${encodeURIComponent(TOKEN)}&fields=${champs}&lat=${lat + dLat}&lng=${lon + dLon}&radius=50&limit=10`
);
for (const img of data.data ?? []) parId.set(img.id, img);
} catch {
/* point sans couverture */
}
await sleep(120);
}
}
if (!parId.size) return null;
const triees = [...parId.values()].sort((a, b) => note(b) - note(a));
return { image: triees[0], total: parId.size };
}
async function nomDeRue(lat, lon) {
try {
const data = await getJSON(`https://api-adresse.data.gouv.fr/reverse/?lon=${lon}&lat=${lat}&type=street`);
const f = data.features?.[0]?.properties;
return f?.name ?? f?.street ?? null;
} catch {
return null;
}
}
// QIDs des communes via sitelinks frwiki (un seul appel batch)
async function qidsCommunes() {
const titres = SPOTS.map((s) => s.titreWiki);
const data = await getJSON(
`https://www.wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=${encodeURIComponent(titres.join('|'))}&props=sitelinks&sitefilter=frwiki&format=json&redirects=yes`
);
const parTitre = {};
for (const [qid, e] of Object.entries(data.entities ?? {})) {
if (e.sitelinks?.frwiki?.title) parTitre[e.sitelinks.frwiki.title] = qid;
}
const redirige = {};
for (const r of data.redirects ?? []) redirige[r.from] = r.to;
const res = {};
for (const s of SPOTS) {
const t = redirige[s.titreWiki] ?? s.titreWiki;
res[s.titreWiki] = parTitre[t] ?? null;
}
return res;
}
const qids = await qidsCommunes();
const lieux = [];
let n = 0;
for (const spot of SPOTS) {
n++;
try {
const centre = await centreCommune(spot);
await sleep(150);
const trouve = await chercherImage(centre.lat, centre.lon);
if (!trouve) {
console.log(`VIDE ${spot.commune} (${spot.region}) — aucune image dans la bbox`);
continue;
}
const img = trouve.image;
const geo = img.computed_geometry ?? img.geometry;
const coords = { lat: geo.coordinates[1], lon: geo.coordinates[0] };
await sleep(150);
const rue = await nomDeRue(coords.lat, coords.lon);
const qid = qids[spot.titreWiki];
lieux.push({
id: `st-${String(n).padStart(2, '0')}`,
nom: rue ? `${rue}, ${spot.commune}` : `Centre de ${spot.commune}`,
nom_creole: `Lari ${spot.commune}`,
region: spot.region,
commune: spot.commune,
coordonnees: coords,
difficulte: spot.difficulte,
mapillary_id: img.id,
credit: {
username: img.creator?.username ?? 'contributeur Mapillary',
captured_at: new Date(img.captured_at).toISOString().slice(0, 10)
},
is_pano: !!img.is_pano,
wikidata_id: qid,
indices: [
{ niveau: 1, texte: spot.indice1 },
{ niveau: 2, texte: spot.indice2 }
],
aire_commune_km2: Math.round(centre.surfaceHa) / 100 // geo.api : hectares → km²
});
console.log(
`OK ${spot.commune.padEnd(24)} img ${img.id} pano=${img.is_pano ? 'oui' : 'NON'} q=${img.quality_score?.toFixed(2) ?? '—'} pool=${trouve.total} qid=${qid ?? 'ABSENT'} rue=${rue ?? '—'}`
);
} catch (e) {
console.log(`ERREUR ${spot.commune}${e.message}`);
}
await sleep(150);
}
writeFileSync(join(ROOT, 'src/lib/server/data/street.json'), JSON.stringify(lieux, null, 2) + '\n');
console.log(`\n${lieux.length} lieux écrits dans src/lib/server/data/street.json`);
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env node
/**
* Validation du corpus JWE (audit OKI : C1, C2, C3, C4c).
* « Fetch, pas recall » : chaque QID, coordonnée et URL photo est vérifié
* par une requête réelle aux API Wikidata / fr.wikipedia / Wikimedia Commons.
*
* Usage : node scripts/validate-lieux.mjs [--photos]
* --photos vérifie aussi les 40 URLs photo (HTTP 200 + licence) — lent.
* Exit code 1 si au moins un FAIL.
*/
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const LIEUX = JSON.parse(readFileSync(join(ROOT, 'src/lib/server/data/lieux.json'), 'utf8'));
const UA = { 'User-Agent': 'JWE-OKI/2.0 (validation corpus; contact: o-k-i.net)' };
const WITH_PHOTOS = process.argv.includes('--photos');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const getJSON = async (url) => {
const res = await fetch(url, { headers: UA });
if (!res.ok) throw new Error(`HTTP ${res.status} sur ${url}`);
return res.json();
};
let fails = 0;
const fail = (id, msg) => {
fails++;
console.log(`FAIL ${id}${msg}`);
};
// --- Schéma (tous les lieux) ------------------------------------------------
const CHAMPS = ['id', 'nom', 'nom_creole', 'region', 'commune', 'coordonnees', 'categorie', 'difficulte', 'wikidata_id', 'photo', 'indices'];
const REGIONS = ['GUADELOUPE', 'MARTINIQUE', 'GUYANE', 'REUNION'];
const ids = new Set();
for (const l of LIEUX) {
for (const c of CHAMPS) if (!(c in l)) fail(l.nom, `champ manquant: ${c}`);
if (ids.has(l.id)) fail(l.nom, `id dupliqué ${l.id}`);
ids.add(l.id);
if (!REGIONS.includes(l.region)) fail(l.nom, `région invalide: ${l.region}`);
if (!['MONUMENT', 'LIEU'].includes(l.categorie)) fail(l.nom, `catégorie invalide`);
if (!['FACILE', 'MOYEN', 'DIFFICILE', 'EXPERT'].includes(l.difficulte)) fail(l.nom, `difficulté invalide`);
if (l.aire_commune_km2 !== undefined && !(l.aire_commune_km2 > 0)) fail(l.nom, `aire_commune_km2 invalide`);
}
console.log(`Schéma : ${LIEUX.length} lieux contrôlés.`);
// --- C1 + C3 : QIDs et coordonnées (un appel batch) --------------------------
const avecQid = LIEUX.filter((l) => l.wikidata_id);
const qids = avecQid.map((l) => l.wikidata_id).join('|');
const data = await getJSON(
`https://www.wikidata.org/w/api.php?action=wbgetentities&ids=${qids}&props=sitelinks|labels|claims&languages=fr&format=json&sitefilter=frwiki`
);
const dist = (a, b) => {
const R = 6371, dLa = ((b.lat - a.lat) * Math.PI) / 180, dLo = ((b.lon - a.lon) * Math.PI) / 180;
const h = Math.sin(dLa / 2) ** 2 + Math.cos((a.lat * Math.PI) / 180) * Math.cos((b.lat * Math.PI) / 180) * Math.sin(dLo / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
};
console.log('\n| Lieu | QID | sitelink frwiki | écart coords | PASS/FAIL |');
console.log('|---|---|---|---|---|');
for (const l of avecQid) {
const e = data.entities[l.wikidata_id];
const site = e?.sitelinks?.frwiki?.title;
const p625 = e?.claims?.P625?.[0]?.mainsnak?.datavalue?.value;
let ok = true;
const notes = [];
if (!e || e.missing !== undefined) {
ok = false;
notes.push('entité absente');
} else if (!site) {
ok = false;
notes.push('pas de sitelink frwiki');
}
if (p625) {
const d = dist(l.coordonnees, { lat: p625.latitude, lon: p625.longitude });
if (d > 0.5) {
ok = false;
notes.push(`écart ${d.toFixed(2)} km > 500 m`);
}
} else notes.push('P625 absent (non bloquant)');
if (!ok) fails++;
console.log(`| ${l.nom} | ${l.wikidata_id} | ${site ?? '—'} | ${notes.join('; ') || '< 500 m'} | ${ok ? 'PASS' : 'FAIL'} |`);
await sleep(100);
}
// --- C2 : les null sont de vrais null ---------------------------------------
console.log('\nLieux à wikidata_id null (preuve absence frwiki) :');
for (const l of LIEUX.filter((x) => !x.wikidata_id)) {
const s = await getJSON(
`https://fr.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent('"' + l.nom + '"')}&srlimit=3&format=json`
);
const exact = s.query.search.some(
(r) => r.title.toLowerCase() === l.nom.toLowerCase()
);
if (exact) fail(l.nom, `un article frwiki « ${l.nom} » EXISTE — le null ne teste pas le Cas B`);
else console.log(`PASS ${l.nom} — aucun article frwiki exact`);
await sleep(400);
}
// --- C4c : photos (optionnel, lent) ------------------------------------------
if (WITH_PHOTOS) {
console.log('\nPhotos (HTTP + licence) :');
for (const l of LIEUX) {
try {
const res = await fetch(l.photo.url, { method: 'HEAD', headers: UA, redirect: 'follow' });
if (!res.ok) fail(l.nom, `photo HTTP ${res.status}`);
else console.log(`PASS photo ${l.nom}`);
} catch (e) {
fail(l.nom, `photo inaccessible: ${e.message}`);
}
await sleep(300);
}
}
console.log(fails ? `\n${fails} FAIL` : '\nTout est conforme.');
process.exit(fails ? 1 : 0);
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env node
/**
* Validation du corpus street (« An lari a », mode Mapillary).
* « Fetch, pas recall » : chaque mapillary_id est revérifié contre l'API
* Mapillary (existence, computed_geometry < 100 m de la vérité curée, crédit
* auteur, flag pano) et chaque wikidata_id contre Wikidata (sitelink frwiki).
*
* Usage : node scripts/validate-street.mjs
* Token lu depuis .env (MAPILLARY_TOKEN ou PUBLIC_MAPILLARY_TOKEN).
* Exit code 1 si au moins un FAIL.
*/
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
const STREET = JSON.parse(readFileSync(join(ROOT, 'src/lib/server/data/street.json'), 'utf8'));
const UA = { 'User-Agent': 'JWE-OKI/2.0 (validation corpus street; contact: o-k-i.net)' };
function chargeEnv() {
try {
for (const ligne of readFileSync(join(ROOT, '.env'), 'utf8').split('\n')) {
const m = ligne.match(/^\s*([A-Z_]+)\s*=\s*(.+?)\s*$/);
if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
}
} catch {
/* pas de .env */
}
}
chargeEnv();
const TOKEN = process.env.MAPILLARY_TOKEN || process.env.PUBLIC_MAPILLARY_TOKEN;
const getJSON = async (url, headers = UA, essais = 3) => {
for (let i = 0; ; i++) {
const res = await fetch(url, { headers });
if (res.ok) return res.json();
// 429 (rate limit Wikidata/Mapillary) ou 5xx : backoff puis retry
if ((res.status === 429 || res.status >= 500) && i < essais - 1) {
await new Promise((r) => setTimeout(r, 2000 * (i + 1)));
continue;
}
throw new Error(`HTTP ${res.status} sur ${url}`);
}
};
let fails = 0;
const fail = (id, msg) => {
fails++;
console.log(`FAIL ${id}${msg}`);
};
const distKm = (a, b) => {
const R = 6371,
dLa = ((b.lat - a.lat) * Math.PI) / 180,
dLo = ((b.lon - a.lon) * Math.PI) / 180;
const h =
Math.sin(dLa / 2) ** 2 +
Math.cos((a.lat * Math.PI) / 180) * Math.cos((b.lat * Math.PI) / 180) * Math.sin(dLo / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(h));
};
// --- Schéma ------------------------------------------------------------------
const CHAMPS = ['id', 'nom', 'nom_creole', 'region', 'commune', 'coordonnees', 'difficulte', 'mapillary_id', 'credit', 'wikidata_id', 'indices'];
const REGIONS = ['GUADELOUPE', 'MARTINIQUE', 'GUYANE', 'REUNION'];
const ids = new Set();
const mlyIds = new Set();
for (const l of STREET) {
for (const c of CHAMPS) if (!(c in l)) fail(l.nom, `champ manquant: ${c}`);
if (ids.has(l.id)) fail(l.nom, `id dupliqué ${l.id}`);
ids.add(l.id);
if (mlyIds.has(l.mapillary_id)) fail(l.nom, `mapillary_id dupliqué ${l.mapillary_id}`);
mlyIds.add(l.mapillary_id);
if (!REGIONS.includes(l.region)) fail(l.nom, `région invalide: ${l.region}`);
if (!['FACILE', 'MOYEN', 'DIFFICILE', 'EXPERT'].includes(l.difficulte)) fail(l.nom, `difficulté invalide`);
if (!l.wikidata_id) fail(l.nom, `wikidata_id null (le mode street documente la commune)`);
if (!(l.aire_commune_km2 > 0)) fail(l.nom, `aire_commune_km2 invalide`);
}
const parRegion = Object.groupBy(STREET, (l) => l.region);
for (const r of REGIONS) {
const n = parRegion[r]?.length ?? 0;
if (n < 3) fail(r, `seulement ${n} lieux (< 3)`);
}
console.log(`Schéma : ${STREET.length} lieux contrôlés (${REGIONS.map((r) => `${r}=${parRegion[r]?.length ?? 0}`).join(', ')}).`);
if (!TOKEN) {
console.log('Token Mapillary absent — vérifications API sautées (schéma seul).');
} else {
// --- Mapillary : existence, géométrie, crédit, pano -------------------------
console.log('\n| Lieu | mapillary_id | écart coords | crédit | pano | PASS/FAIL |');
console.log('|---|---|---|---|---|---|');
for (const l of STREET) {
try {
const img = await getJSON(
`https://graph.mapillary.com/${l.mapillary_id}?access_token=${encodeURIComponent(TOKEN)}&fields=id,is_pano,captured_at,computed_geometry,creator`
);
const geo = img.computed_geometry;
const d = distKm(l.coordonnees, { lat: geo.coordinates[1], lon: geo.coordinates[0] });
const notes = [];
let ok = true;
if (d > 0.1) {
ok = false;
notes.push(`écart ${(d * 1000).toFixed(0)} m > 100 m`);
}
if ((img.creator?.username ?? null) !== l.credit.username) {
ok = false;
notes.push(`crédit « ${l.credit.username} » ≠ « ${img.creator?.username} »`);
}
if (!!img.is_pano !== !!l.is_pano) notes.push(`pano API=${img.is_pano} corpus=${l.is_pano} (non bloquant)`);
if (!ok) fail(l.nom, notes.join(' ; '));
console.log(`| ${l.nom} | ${l.mapillary_id} | ${(d * 1000).toFixed(0)} m | ${l.credit.username} | ${img.is_pano ? 'oui' : 'non'} | ${ok ? 'PASS' : 'FAIL'} |`);
} catch (e) {
fail(l.nom, `Mapillary : ${e.message}`);
}
await new Promise((r) => setTimeout(r, 120));
}
}
// --- Wikidata : sitelink frwiki pour chaque commune ---------------------------
const qids = STREET.map((l) => l.wikidata_id).filter(Boolean).join('|');
const data = await getJSON(
`https://www.wikidata.org/w/api.php?action=wbgetentities&ids=${qids}&props=sitelinks&sitefilter=frwiki&format=json`
);
console.log('\n| Lieu | QID commune | sitelink frwiki | PASS/FAIL |');
console.log('|---|---|---|---|');
for (const l of STREET) {
const site = data.entities?.[l.wikidata_id]?.sitelinks?.frwiki?.title;
if (!site) fail(l.nom, `${l.wikidata_id} sans sitelink frwiki`);
console.log(`| ${l.nom} | ${l.wikidata_id} | ${site ?? 'ABSENT'} | ${site ? 'PASS' : 'FAIL'} |`);
}
console.log(fails ? `\n${fails} FAIL.` : '\nTout est conforme.');
process.exit(fails ? 1 : 0);
+12
View File
@@ -0,0 +1,12 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0b3d2e" />
<link rel="icon" href="%sveltekit.assets%/favicon.ico" />
<link rel="manifest" href="%sveltekit.assets%/manifest.webmanifest" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
+339
View File
@@ -0,0 +1,339 @@
<script lang="ts" module>
import geoJson from '$lib/map/regions-geo.json';
import type { Region } from '$lib/types';
/** Point à afficher sur la carte (bilan du défi). */
export interface MarqueurCarte {
lat: number;
lon: number;
type: 'reel' | 'guess';
label?: string;
/** Numéro de manche : relie le guess au réel de même paire. */
paire?: number;
}
export type SelectionCarte = Region | 'TOUTES' | null;
type Anneau = [number, number][];
interface RegionGeo {
nom: string;
creole: string;
polygons: Anneau[];
}
const GEO = geoJson as unknown as Record<Region, RegionGeo>;
/**
* Carte SVG statique des 4 régions, écrite from scratch pour JWE (ADR-002) :
* projection équirectangulaire simple par région, chaque région dans son
* propre inset (les 4 régions sont à ~12 000 km d'écart — la disposition
* 2×2 est un choix cartographique assumé, sans prétention d'échelle commune).
* Tout est précalculé au chargement du module : rendu SSR sans aucun JS client.
*/
const VUE_L = 600; // largeur du viewBox
const CELLULE_L = VUE_L / 2; // 2 colonnes
const CELLULE_H = 310; // 2 lignes
const MARGE = 14; // respiration autour des formes dans un inset
const HAUTEUR_NOM = 26; // bandeau du nom de région en bas d'inset
/** Ordre des insets : Antilles en haut, Guyane et Réunion en bas. */
const ORDRE: Region[] = ['GUADELOUPE', 'MARTINIQUE', 'GUYANE', 'REUNION'];
interface Inset {
region: Region;
nom: string;
creole: string;
colonne: number;
rang: number;
/** Chemins SVG (attributs `d`) des communes, déjà projetés dans le viewBox. */
chemins: string[];
/** Position du libellé de région. */
nomX: number;
nomY: number;
/** Bornes lon/lat brutes — sert à affecter un marqueur à son inset. */
bornes: [number, number, number, number];
/** Projection lon/lat → coordonnées du viewBox. */
projeter: (lon: number, lat: number) => [number, number];
}
const r1 = (n: number) => Math.round(n * 10) / 10;
function construireInsets(): Inset[] {
return ORDRE.map((region, i) => {
const { nom, creole, polygons } = GEO[region];
let minLon = Infinity;
let maxLon = -Infinity;
let minLat = Infinity;
let maxLat = -Infinity;
for (const poly of polygons) {
for (const [lon, lat] of poly) {
if (lon < minLon) minLon = lon;
if (lon > maxLon) maxLon = lon;
if (lat < minLat) minLat = lat;
if (lat > maxLat) maxLat = lat;
}
}
// Équirectangulaire : un degré de longitude vaut cos(lat) × un degré de latitude.
const cos0 = Math.cos(((minLat + maxLat) / 2) * (Math.PI / 180));
const largeurGeo = (maxLon - minLon) * cos0;
const hauteurGeo = maxLat - minLat;
const colonne = i % 2;
const rang = Math.floor(i / 2);
const dispoL = CELLULE_L - 2 * MARGE;
const dispoH = CELLULE_H - 2 * MARGE - HAUTEUR_NOM;
const echelle = Math.min(dispoL / largeurGeo, dispoH / hauteurGeo);
// Centre les formes dans l'espace disponible de l'inset.
const origX = colonne * CELLULE_L + MARGE + (dispoL - largeurGeo * echelle) / 2;
const origY = rang * CELLULE_H + MARGE + (dispoH - hauteurGeo * echelle) / 2;
const projeter = (lon: number, lat: number): [number, number] => [
r1(origX + (lon - minLon) * cos0 * echelle),
r1(origY + (maxLat - lat) * echelle)
];
const chemins = polygons.map(
(poly) =>
'M' + poly.map(([lon, lat]) => projeter(lon, lat).join(',')).join('L') + 'Z'
);
return {
region,
nom,
creole,
colonne,
rang,
chemins,
nomX: colonne * CELLULE_L + CELLULE_L / 2,
nomY: (rang + 1) * CELLULE_H - 7,
bornes: [minLon, minLat, maxLon, maxLat],
projeter
};
});
}
const INSETS = construireInsets();
const VUE_H = CELLULE_H * 2;
/** Projette un point dans l'inset de sa région ; null si hors de toute région (omis). */
function projeterMarqueur(lon: number, lat: number): [number, number] | null {
for (const ins of INSETS) {
const [minLon, minLat, maxLon, maxLat] = ins.bornes;
if (lon >= minLon && lon <= maxLon && lat >= minLat && lat <= maxLat) {
return ins.projeter(lon, lat);
}
}
return null;
}
</script>
<script lang="ts">
import { t } from '$lib/i18n/store.svelte';
interface Props {
/** Région sélectionnée (liaison bidirectionnelle) — ignorée si `selectionnable` est faux. */
selection?: SelectionCarte;
/** Vrai (défaut) : chaque région est un vrai <button> ; faux : carte de récap statique. */
selectionnable?: boolean;
marqueurs?: MarqueurCarte[];
attribution?: string;
}
let {
selection = $bindable<SelectionCarte>(null),
selectionnable = true,
marqueurs = [],
attribution = '© contributeurs OpenStreetMap / données publiques'
}: Props = $props();
let survol = $state<Region | null>(null);
interface MarqueurProjete extends MarqueurCarte {
x: number;
y: number;
cle: string;
}
// Points hors de tout inset : omis silencieusement (consigne ADR-002).
const marqueursProjetes = $derived(
marqueurs.flatMap((m, i): MarqueurProjete[] => {
const pt = projeterMarqueur(m.lon, m.lat);
return pt ? [{ ...m, x: pt[0], y: pt[1], cle: `${i}-${m.type}` }] : [];
})
);
// Ligne guess → réel pour chaque paire complète (même numéro de manche).
const lignes = $derived.by(() => {
const paires = new Map<number, Partial<Record<'guess' | 'reel', [number, number]>>>();
for (const m of marqueursProjetes) {
if (m.paire == null) continue;
const entree = paires.get(m.paire) ?? {};
entree[m.type] = [m.x, m.y];
paires.set(m.paire, entree);
}
const out: { paire: number; x1: number; y1: number; x2: number; y2: number }[] = [];
for (const [paire, e] of paires) {
if (e.guess && e.reel) {
out.push({ paire, x1: e.guess[0], y1: e.guess[1], x2: e.reel[0], y2: e.reel[1] });
}
}
return out;
});
</script>
<figure class="carte-regions">
<div class="cadre">
<svg
viewBox="0 0 {VUE_L} {VUE_H}"
role={selectionnable ? undefined : 'img'}
aria-hidden={selectionnable ? 'true' : undefined}
aria-label={selectionnable ? undefined : t().carte.carteRegionsLabel}
>
{#each INSETS as ins (ins.region)}
<g
class="region"
class:survolee={selectionnable && survol === ins.region}
class:choisie={selectionnable && selection === ins.region}
>
{#each ins.chemins as d (d)}
<path {d} />
{/each}
</g>
{/each}
{#each lignes as l (l.paire)}
<line class="lien-paire" x1={l.x1} y1={l.y1} x2={l.x2} y2={l.y2} />
{/each}
{#each marqueursProjetes as m (m.cle)}
<g class="marqueur {m.type}">
{#if m.label}<title>{m.label}</title>{/if}
<circle cx={m.x} cy={m.y} r="8" />
{#if m.paire != null}
<text x={m.x} y={m.y + 3.5}>{m.paire}</text>
{/if}
</g>
{/each}
{#each INSETS as ins (ins.region)}
<text
class="nom-region"
class:choisie={selectionnable && selection === ins.region}
x={ins.nomX}
y={ins.nomY}>{t().regions[ins.region]}</text
>
{/each}
</svg>
{#if selectionnable}
<!-- Un vrai <button> par région, calé sur son inset : clavier + lecteur d'écran.
Le nom accessible est bilingue (FR / créole), le libellé visible suit la langue. -->
{#each INSETS as ins (ins.region)}
<button
type="button"
class="zone-region"
style="left: {ins.colonne * 50}%; top: {ins.rang * 50}%"
aria-pressed={selection === ins.region}
aria-label="{ins.nom} / {ins.creole}"
onclick={() => (selection = ins.region)}
onmouseenter={() => (survol = ins.region)}
onmouseleave={() => (survol = null)}
onfocus={() => (survol = ins.region)}
onblur={() => (survol = null)}
></button>
{/each}
{/if}
</div>
<figcaption class="attribution">{attribution}</figcaption>
</figure>
<style>
.carte-regions {
margin: 0;
width: 100%;
}
.cadre {
position: relative;
width: 100%;
}
svg {
display: block;
width: 100%;
height: auto;
}
/* — Régions : tokens OKI, aucun bleu « Google » — */
.region path {
fill: var(--oki-vert-doux);
stroke: var(--oki-vert-clair);
stroke-width: 0.9;
}
.region.survolee path {
fill: var(--oki-bleu-doux);
stroke: var(--oki-bleu);
}
.region.choisie path {
fill: var(--oki-vert-clair);
stroke: var(--oki-vert-doux);
}
.nom-region {
fill: var(--oki-vert);
font-size: 15px;
font-weight: 700;
text-anchor: middle;
}
.nom-region.choisie {
text-decoration: underline;
}
/* — Marqueurs du récap (guess = corail, réel = vert, comme la légende du bilan) — */
.lien-paire {
stroke: var(--oki-encre-doux);
stroke-width: 2;
stroke-dasharray: 6 4;
fill: none;
}
.marqueur circle {
stroke: var(--oki-blanc);
stroke-width: 2;
}
.marqueur.guess circle {
fill: var(--oki-corail);
}
.marqueur.reel circle {
fill: var(--oki-vert);
}
.marqueur text {
fill: #fff;
font-size: 10px;
font-weight: 800;
text-anchor: middle;
pointer-events: none;
}
/* Boutons transparents calés sur les insets (2×2) */
.zone-region {
position: absolute;
width: 50%;
height: 50%;
padding: 0;
border: none;
background: transparent;
border-radius: var(--oki-radius);
cursor: pointer;
}
.zone-region:focus-visible {
outline: 3px solid var(--oki-bleu);
outline-offset: -3px;
}
.attribution {
margin: 0.3rem 0 0;
font-size: 0.72rem;
color: var(--oki-encre-doux);
text-align: right;
}
</style>
+434
View File
@@ -0,0 +1,434 @@
<script lang="ts">
import { onMount } from 'svelte';
import { env } from '$env/dynamic/public';
import { t } from '$lib/i18n/store.svelte';
import { MAX_BOUNDS, MIN_ZOOM, REGION_BOUNDS, REGIONS } from '$lib/map/regions';
import styleOki from '$lib/map/style-oki.json';
import type { Coordonnees, Region } from '$lib/types';
import type { Map as MLMap, Marker, StyleSpecification } from 'maplibre-gl';
interface Paire {
from: Coordonnees;
to: Coordonnees;
label?: string;
}
interface MarqueurInfo {
id: string;
lat: number;
lon: number;
label: string;
}
interface Props {
guess?: Coordonnees | null;
real?: Coordonnees | null;
distanceKm?: number | null;
interactive?: boolean;
pairs?: Paire[];
markers?: MarqueurInfo[];
onguess?: (c: Coordonnees) => void;
onvalidate?: () => void;
onmarkerclick?: (id: string) => void;
}
let {
guess = $bindable(null),
real = null,
distanceKm = null,
interactive = true,
pairs = [],
markers = [],
onguess,
onvalidate,
onmarkerclick
}: Props = $props();
let conteneur: HTMLDivElement;
let map: MLMap | null = null;
let ml: typeof import('maplibre-gl') | null = null;
let guessMarker: Marker | null = null;
let realMarker: Marker | null = null;
let explorerMarkers: Marker[] = [];
const SRC_LIGNE = 'jwe-ligne';
const SRC_PAIRES = 'jwe-paires';
const reducedMotion =
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function styleUrl(): string | StyleSpecification {
// Bascule vers un tileserver auto-hébergé sans changement de code.
if (env.PUBLIC_TILES_URL) return env.PUBLIC_TILES_URL;
return styleOki as unknown as StyleSpecification;
}
function ensureSource(id: string): void {
if (map && !map.getSource(id)) {
map.addSource(id, {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] }
});
}
}
function setGeoJSON(id: string, data: GeoJSON.FeatureCollection): void {
const src = map?.getSource(id) as import('maplibre-gl').GeoJSONSource | undefined;
src?.setData(data);
}
function ligneFeature(from: Coordonnees, to: Coordonnees, props: GeoJSON.GeoJsonProperties): GeoJSON.Feature {
return {
type: 'Feature',
properties: props,
geometry: { type: 'LineString', coordinates: [[from.lon, from.lat], [to.lon, to.lat]] }
};
}
function pointFeature(c: Coordonnees, props: GeoJSON.GeoJsonProperties): GeoJSON.Feature {
return {
type: 'Feature',
properties: props,
geometry: { type: 'Point', coordinates: [c.lon, c.lat] }
};
}
function dessinerRevelation(): void {
if (!map || !ml || !real) return;
ensureSource(SRC_LIGNE);
if (!map.getLayer('jwe-ligne-line')) {
map.addLayer({
id: 'jwe-ligne-line',
type: 'line',
source: SRC_LIGNE,
filter: ['==', ['geometry-type'], 'LineString'],
paint: { 'line-color': '#e4572e', 'line-width': 3, 'line-dasharray': [2, 1.5] }
});
map.addLayer({
id: 'jwe-ligne-label',
type: 'symbol',
source: SRC_LIGNE,
filter: ['==', ['geometry-type'], 'Point'],
layout: {
'text-field': ['get', 'etiquette'],
'text-size': 14,
'text-font': ['Noto Sans Regular'],
'text-offset': [0, -1.4]
},
paint: { 'text-color': '#0b3d2e', 'text-halo-color': '#fffdf8', 'text-halo-width': 2 }
});
}
const features: GeoJSON.Feature[] = [];
if (guess) {
features.push(ligneFeature(guess, real, null));
if (distanceKm !== null) {
// Étiquette de distance au milieu de la ligne guess ↔ réel
features.push(
pointFeature(
{ lat: (guess.lat + real.lat) / 2, lon: (guess.lon + real.lon) / 2 },
{ etiquette: `${distanceKm} km` }
)
);
}
}
setGeoJSON(SRC_LIGNE, { type: 'FeatureCollection', features });
// Marqueur vert = position réelle ; le marqueur corail du joueur RESTE
// à sa position : la comparaison visuelle guess ↔ réel est le cœur du jeu.
realMarker?.remove();
realMarker = new ml.Marker({ color: '#0b3d2e' }).setLngLat([real.lon, real.lat]).addTo(map);
if (guess) {
const bounds = new ml.LngLatBounds(
[Math.min(guess.lon, real.lon), Math.min(guess.lat, real.lat)],
[Math.max(guess.lon, real.lon), Math.max(guess.lat, real.lat)]
);
map.fitBounds(bounds, { padding: 80, duration: reducedMotion ? 0 : 900, maxZoom: 12 });
} else {
map.easeTo({ center: [real.lon, real.lat], zoom: 11, duration: reducedMotion ? 0 : 900 });
}
}
function nettoyerRevelation(): void {
realMarker?.remove();
realMarker = null;
setGeoJSON(SRC_LIGNE, { type: 'FeatureCollection', features: [] });
}
function syncGuessMarker(): void {
if (!map || !ml) return;
if (guess) {
if (!guessMarker) {
guessMarker = new ml.Marker({ color: '#e4572e', draggable: true })
.setLngLat([guess.lon, guess.lat])
.addTo(map);
guessMarker.on('dragend', () => {
const ll = guessMarker?.getLngLat();
if (ll) {
guess = { lat: ll.lat, lon: ll.lng };
onguess?.(guess);
}
});
} else {
guessMarker.setLngLat([guess.lon, guess.lat]);
}
guessMarker.setDraggable(interactive && !real);
} else {
guessMarker?.remove();
guessMarker = null;
}
}
function syncPaires(): void {
if (!map || !ml) return;
ensureSource(SRC_PAIRES);
if (!map.getLayer('jwe-paires-line')) {
map.addLayer({
id: 'jwe-paires-line',
type: 'line',
source: SRC_PAIRES,
filter: ['==', ['geometry-type'], 'LineString'],
paint: { 'line-color': '#5a6b62', 'line-width': 2, 'line-dasharray': [2, 1.5] }
});
map.addLayer({
id: 'jwe-paires-points',
type: 'circle',
source: SRC_PAIRES,
filter: ['==', ['geometry-type'], 'Point'],
paint: {
'circle-radius': 7,
'circle-color': ['get', 'couleur'],
'circle-stroke-color': '#fffdf8',
'circle-stroke-width': 2
}
});
}
const features: GeoJSON.Feature[] = [];
for (const p of pairs) {
features.push(ligneFeature(p.from, p.to, null));
features.push(pointFeature(p.from, { couleur: '#e4572e' })); // joueur
features.push(pointFeature(p.to, { couleur: '#0b3d2e' })); // réel
}
setGeoJSON(SRC_PAIRES, { type: 'FeatureCollection', features });
if (pairs.length > 0) {
const b = new ml.LngLatBounds();
for (const p of pairs) {
b.extend([p.from.lon, p.from.lat]);
b.extend([p.to.lon, p.to.lat]);
}
map.fitBounds(b, { padding: 60, duration: reducedMotion ? 0 : 800 });
}
}
function syncExplorerMarkers(): void {
if (!map || !ml) return;
for (const m of explorerMarkers) m.remove();
explorerMarkers = [];
for (const info of markers) {
const el = document.createElement('button');
el.type = 'button';
el.className = 'marqueur-explorer';
el.setAttribute('aria-label', info.label);
const mk = new ml.Marker({ element: el, color: '#175e70' })
.setLngLat([info.lon, info.lat])
.addTo(map!);
el.addEventListener('click', (e) => {
e.stopPropagation();
onmarkerclick?.(info.id);
});
explorerMarkers.push(mk);
}
}
function sauterVers(region: Region): void {
const b = REGION_BOUNDS[region];
map?.fitBounds(
[
[b[0], b[1]],
[b[2], b[3]]
],
{ duration: reducedMotion ? 0 : 800 }
);
}
function onKeydown(e: KeyboardEvent): void {
if (!map) return;
const pas = 140; // pixels de déplacement
if (e.key === 'Enter') {
e.preventDefault();
onvalidate?.();
return;
}
const dirs: Record<string, [number, number]> = {
ArrowUp: [0, -pas],
ArrowDown: [0, pas],
ArrowLeft: [-pas, 0],
ArrowRight: [pas, 0]
};
const d = dirs[e.key];
if (!d) return;
e.preventDefault();
if (guessMarker && interactive && !real) {
// Déplacer le marqueur : conversion écran → géo pour garder un pas constant
const ll = guessMarker.getLngLat();
const pt = map.project([ll.lng, ll.lat]);
const nv = map.unproject([pt.x + d[0], pt.y + d[1]]);
guess = { lat: nv.lat, lon: nv.lng };
onguess?.(guess);
} else {
map.panBy(d, { duration: 100 });
}
}
onMount(() => {
let detruit = false;
// Lazy load : MapLibre (JS + CSS) n'est chargé que sur les écrans avec carte.
void (async () => {
const [mod] = await Promise.all([import('maplibre-gl'), import('maplibre-gl/dist/maplibre-gl.css')]);
if (detruit) return;
ml = mod;
map = new mod.Map({
container: conteneur,
style: styleUrl(),
center: [-58, 0],
zoom: 3.6,
minZoom: MIN_ZOOM,
maxBounds: [
[MAX_BOUNDS[0], MAX_BOUNDS[1]],
[MAX_BOUNDS[2], MAX_BOUNDS[3]]
],
attributionControl: { compact: true },
// Libellés FR/créole des contrôles natifs (sinon « Zoom in/out » en anglais)
locale: {
'NavigationControl.ZoomIn': t().carte.zoomIn,
'NavigationControl.ZoomOut': t().carte.zoomOut
}
});
map.addControl(new mod.NavigationControl({ showCompass: false }), 'top-left');
map.on('click', (e) => {
if (!interactive || real) return;
guess = { lat: e.lngLat.lat, lon: e.lngLat.lng };
onguess?.(guess);
});
map.on('load', () => {
syncGuessMarker();
syncPaires();
syncExplorerMarkers();
if (real) dessinerRevelation();
});
})();
return () => {
detruit = true;
map?.remove();
map = null;
};
});
let ancienReal: Coordonnees | null = null;
$effect(() => {
// Lecture inconditionnelle de `real` : au montage la carte n'existe pas
// encore, et un retour anticipé avant toute lecture réactive ferait que
// Svelte n'enregistre aucune dépendance — l'effet ne serait jamais relancé.
// (isStyleLoaded et non loaded : loaded() reste faux pendant le chargement
// des tuiles, ce qui ferait rater le dessin juste après un zoom/pan.)
void real;
if (!map || !map.isStyleLoaded()) return;
if (real && !ancienReal) dessinerRevelation();
if (!real && ancienReal) nettoyerRevelation();
ancienReal = real;
});
$effect(() => {
if (map?.loaded()) syncGuessMarker();
void guess;
void interactive;
});
$effect(() => {
if (map?.loaded()) syncPaires();
void pairs;
});
$effect(() => {
if (map?.loaded()) syncExplorerMarkers();
void markers;
});
</script>
<div class="carte-wrap">
<!-- La zone carte est volontairement focusable : flèches = déplacer le marqueur, Entrée = valider -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div
class="carte"
bind:this={conteneur}
role="application"
aria-label={t().carte.ariaLabel}
tabindex="0"
onkeydown={onKeydown}
></div>
<div class="sauts" role="group" aria-label={t().carte.sautRegion}>
{#each REGIONS as region (region)}
<button type="button" class="saut" onclick={() => sauterVers(region)}>
{t().regions[region]}
</button>
{/each}
</div>
</div>
<style>
.carte-wrap {
position: relative;
width: 100%;
height: 100%;
}
.carte {
width: 100%;
height: 100%;
border-radius: var(--oki-radius);
overflow: hidden;
}
.sauts {
position: absolute;
bottom: 0.75rem;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
justify-content: center;
padding: 0 0.5rem;
}
.saut {
background: rgba(255, 253, 248, 0.94);
color: var(--oki-vert);
border: 1px solid var(--oki-sable-fonce);
border-radius: 999px;
padding: 0.35rem 0.8rem;
font-size: 0.8rem;
font-weight: 650;
cursor: pointer;
box-shadow: var(--oki-ombre);
}
.saut:hover {
background: var(--oki-vert-doux);
}
:global(.marqueur-explorer) {
width: 26px;
height: 26px;
border-radius: 50%;
border: 2.5px solid var(--oki-blanc);
background: var(--oki-bleu);
cursor: pointer;
box-shadow: var(--oki-ombre);
}
:global(.marqueur-explorer:hover),
:global(.marqueur-explorer:focus-visible) {
background: var(--oki-vert-clair);
}
</style>
+43
View File
@@ -0,0 +1,43 @@
<script lang="ts">
import { t } from '$lib/i18n/store.svelte';
import { getLang, setLang, type Lang } from '$lib/i18n/store.svelte';
</script>
<div class="lang-switch" role="group" aria-label="Langue / Lang">
{#each ['fr', 'gcf'] as l (l)}
<button
type="button"
class:actif={getLang() === l}
aria-pressed={getLang() === l}
onclick={() => setLang(l as Lang)}
>
{t().langue[l as Lang]}
</button>
{/each}
</div>
<style>
.lang-switch {
display: flex;
gap: 0.25rem;
background: var(--oki-vert-doux);
border-radius: 999px;
padding: 0.2rem;
}
button {
border: none;
background: transparent;
color: var(--oki-vert);
border-radius: 999px;
padding: 0.3rem 0.75rem;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
}
button.actif {
background: var(--oki-vert);
color: #fff;
}
</style>
+63
View File
@@ -0,0 +1,63 @@
<script lang="ts">
import type { Photo } from '$lib/types';
interface Props {
photo: Photo;
revealed?: boolean;
}
let { photo, revealed = false }: Props = $props();
// Proxy /api/photo : 3 largeurs disponibles, le navigateur choisit (C4).
const srcset = $derived(
photo.srcset
? Object.entries(photo.srcset)
.map(([w, u]) => `${u} ${w}w`)
.join(', ')
: undefined
);
</script>
<figure class="photo-panel">
<img
src={photo.url}
{srcset}
sizes="(min-width: 768px) 50vw, 100vw"
alt={photo.alt}
loading="lazy"
decoding="async"
/>
{#if revealed}
<figcaption>{photo.credit}</figcaption>
{/if}
</figure>
<style>
.photo-panel {
position: relative;
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--oki-vert);
border-radius: var(--oki-radius);
}
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
figcaption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 0.4rem 0.8rem;
font-size: 0.72rem;
color: #fff;
background: linear-gradient(transparent, rgba(11, 61, 46, 0.85));
}
</style>
+123
View File
@@ -0,0 +1,123 @@
<script lang="ts">
import WikiFiche from './WikiFiche.svelte';
import { t } from '$lib/i18n/store.svelte';
import type { GuessResult } from '$lib/types';
interface Props {
result: GuessResult;
labelBouton?: string;
creditPhoto?: string;
onsuivant?: () => void;
}
let { result, labelBouton, creditPhoto, onsuivant }: Props = $props();
</script>
<section class="resultat" aria-live="polite">
<header class="score-bloc">
<p class="bravo">{result.score > 0 ? t().micro.bravo : t().micro.kiteSaYe}</p>
<p class="score">
<span class="valeur">{result.score}</span>
<span class="unite">{t().resultat.points}</span>
</p>
{#if result.distanceKm !== null}
<p class="distance">{t().resultat.distance} : {result.distanceKm} {t().resultat.km}</p>
{#if result.radiusEffKm !== null}
<p class="rayon">{t().resultat.rayonScore} : {result.radiusEffKm} {t().resultat.km}</p>
{/if}
{/if}
<p class="lieu">
<strong>{result.nom}</strong>
{#if result.nom_creole && result.nom_creole !== result.nom}
<span class="creole"> · {result.nom_creole}</span>
{/if}
<br />
{t().resultat.commune} : {result.commune}{t().regions[result.region]}
</p>
</header>
{#key result.nom}
<WikiFiche
nom={result.nom}
wikidataId={result.wikidata_id}
tonPositif={result.score > 0 ? t().resultat.trouve : t().resultat.aDecouvrir}
/>
{/key}
{#if creditPhoto}
<p class="credit-photo">{creditPhoto}</p>
{/if}
{#if onsuivant}
<button type="button" class="btn btn-primaire suivant" onclick={onsuivant}>
{labelBouton ?? t().resultat.suivant}
</button>
{/if}
</section>
<style>
.resultat {
display: flex;
flex-direction: column;
gap: 1rem;
}
.score-bloc {
text-align: center;
}
.bravo {
margin: 0;
font-size: 1.3rem;
font-weight: 700;
color: var(--oki-vert-clair);
}
.score {
margin: 0.2rem 0;
}
.score .valeur {
font-size: 2.6rem;
font-weight: 800;
color: var(--oki-vert);
}
.score .unite {
font-size: 1rem;
color: var(--oki-encre-doux);
margin-left: 0.3rem;
}
.distance {
margin: 0;
color: var(--oki-encre-doux);
}
.rayon {
margin: 0.1rem 0 0;
font-size: 0.82rem;
color: var(--oki-encre-doux);
}
.credit-photo {
margin: 0;
font-size: 0.72rem;
color: var(--oki-encre-doux);
text-align: center;
}
.lieu {
margin: 0.5rem 0 0;
}
.creole {
color: var(--oki-vert-clair);
font-style: italic;
}
.suivant {
align-self: center;
min-width: 220px;
}
</style>
+115
View File
@@ -0,0 +1,115 @@
<script lang="ts">
import { onMount } from 'svelte';
import { env } from '$env/dynamic/public';
import { t } from '$lib/i18n/store.svelte';
import type { Viewer } from 'mapillary-js';
interface Props {
mapillaryId: string;
credit?: string;
}
let { mapillaryId, credit }: Props = $props();
let conteneur: HTMLDivElement;
let viewer: Viewer | null = null;
let etat = $state<'chargement' | 'pret' | 'erreur' | 'token'>('chargement');
onMount(() => {
let detruit = false;
// Lazy load : mapillary-js (JS + CSS) n'est chargé que sur l'écran de jeu street.
void (async () => {
const token = env.PUBLIC_MAPILLARY_TOKEN;
if (!token) {
etat = 'token';
return;
}
try {
const [mod] = await Promise.all([
import('mapillary-js'),
import('mapillary-js/dist/mapillary.css')
]);
if (detruit) return;
// cover désactivé : la photo s'affiche directement, sans écran d'intro.
viewer = new mod.Viewer({
accessToken: token,
container: conteneur,
component: { cover: false }
});
// moveTo rejette si l'image a été retirée de Mapillary entre-temps.
await viewer.moveTo(mapillaryId);
if (detruit) return;
etat = 'pret';
} catch {
if (!detruit) etat = 'erreur';
}
})();
return () => {
detruit = true;
viewer?.remove();
viewer = null;
};
});
</script>
<figure class="street-panel">
<div
bind:this={conteneur}
class="visionneuse"
role="application"
aria-label={t().jeu.streetAriaLabel}
></div>
{#if etat !== 'pret'}
<div class="voile">
<p>
{#if etat === 'chargement'}{t().jeu.streetChargement}
{:else if etat === 'token'}{t().jeu.streetToken}
{:else}{t().jeu.streetErreur}{/if}
</p>
</div>
{/if}
{#if credit && etat === 'pret'}
<figcaption>{credit}</figcaption>
{/if}
</figure>
<style>
.street-panel {
position: relative;
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--oki-vert);
border-radius: var(--oki-radius);
}
.visionneuse {
width: 100%;
height: 100%;
}
.voile {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
text-align: center;
color: var(--oki-blanc);
background: var(--oki-vert);
}
figcaption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 0.4rem 0.8rem;
font-size: 0.72rem;
color: #fff;
background: linear-gradient(transparent, rgba(11, 61, 46, 0.85));
pointer-events: none;
}
</style>
+87
View File
@@ -0,0 +1,87 @@
<script lang="ts">
import { onMount } from 'svelte';
interface Props {
dureeMs?: number; // fenêtre du bonus temps (60 s)
actif?: boolean;
}
let { dureeMs = 60000, actif = true }: Props = $props();
let ecoule = $state(0);
let intervalle: ReturnType<typeof setInterval> | null = null;
const depart = Date.now();
// Fraction restante, de 1 (plein) à 0 (vide) — informatif, jamais anxiogène.
let fraction = $derived(Math.max(0, 1 - ecoule / dureeMs));
let termine = $derived(ecoule >= dureeMs);
const R = 15.5;
const C = 2 * Math.PI * R;
/** Temps écoulé en ms (pour le bonus côté /api/guess). */
export function tempsMs(): number {
return Date.now() - depart;
}
onMount(() => {
if (actif) {
intervalle = setInterval(() => {
ecoule = Date.now() - depart;
if (ecoule >= dureeMs && intervalle) {
clearInterval(intervalle);
intervalle = null;
}
}, 250);
}
return () => {
if (intervalle) clearInterval(intervalle);
};
});
</script>
<div class="timer" class:termine role="timer" aria-label="Minuteur" title="Minuteur">
<svg viewBox="0 0 36 36" aria-hidden="true">
<circle class="fond" cx="18" cy="18" r={R} />
<circle
class="reste"
cx="18"
cy="18"
r={R}
stroke-dasharray={C}
stroke-dashoffset={C * (1 - fraction)}
transform="rotate(-90 18 18)"
/>
</svg>
</div>
<style>
.timer {
width: 40px;
height: 40px;
}
svg {
width: 100%;
height: 100%;
display: block;
}
.fond {
fill: rgba(255, 253, 248, 0.85);
stroke: var(--oki-sable-fonce);
stroke-width: 3;
}
.reste {
fill: none;
stroke: var(--oki-vert-clair); /* couleur douce, calm technology */
stroke-width: 3;
stroke-linecap: round;
transition: stroke-dashoffset 0.25s linear;
}
.termine .reste {
stroke: var(--oki-sable-fonce);
}
</style>
+224
View File
@@ -0,0 +1,224 @@
<script lang="ts">
import { onMount } from 'svelte';
import { t } from '$lib/i18n/store.svelte';
import type { WikiSummary } from '$lib/types';
interface Props {
nom: string;
wikidataId: string | null;
tonPositif?: string;
tonNeutre?: string;
}
let { nom, wikidataId, tonPositif, tonNeutre }: Props = $props();
// undefined = chargement, null = pas de fiche, WikiSummary = Cas A
let wiki = $state<WikiSummary | null | undefined>(undefined);
// Cas intermédiaire (audit A3) : QID présent, fiche Wikidata existante,
// mais pas d'article Wikipédia en français (404 {reason:'no-frwiki'}).
let sansFrwiki = $state(false);
onMount(() => {
if (!wikidataId) {
wiki = null;
return;
}
let annule = false;
void (async () => {
try {
const res = await fetch(`/api/wiki/${wikidataId}`);
if (annule) return;
if (res.ok) {
wiki = (await res.json()) as WikiSummary;
} else {
if (res.status === 404) {
try {
const corps = (await res.json()) as { reason?: string };
sansFrwiki = corps.reason === 'no-frwiki';
} catch {
sansFrwiki = false;
}
}
wiki = null;
}
} catch {
if (!annule) wiki = null;
}
})();
return () => {
annule = true;
};
});
const lienContribution = $derived(
`https://fr.wikipedia.org/w/index.php?search=${encodeURIComponent(nom)}&title=Sp%C3%A9cial:Recherche`
);
const lienWikidata = $derived(`https://www.wikidata.org/wiki/${wikidataId}`);
</script>
{#if wiki === undefined}
<div class="panneau chargement">
<p>{t().explorer.chargerFiche}</p>
</div>
{:else if wiki}
<!-- Cas A : fiche Wikipédia existante -->
<article class="panneau cas-a">
<h2>
<a href={wiki.url} target="_blank" rel="noopener noreferrer">{wiki.title}</a>
</h2>
{#if tonPositif || tonNeutre}
<p class="ton">{tonPositif ?? tonNeutre}</p>
{/if}
{#if wiki.thumbnail}
<img src={wiki.thumbnail} alt="" loading="lazy" decoding="async" />
{/if}
<p class="extrait">{wiki.extract}</p>
<a class="lien-wiki" href={wiki.url} target="_blank" rel="noopener noreferrer">
{t().resultat.lireWiki}
</a>
</article>
{:else if sansFrwiki}
<!-- Variante Cas B : fiche Wikidata OK mais pas d'article FR — appel à traduire/créer -->
<article class="panneau cas-b">
<h2><span class="icone" aria-hidden="true"></span> {t().lacuneFr.titre}</h2>
<p class="texte">{t().lacuneFr.texte}</p>
<div class="ctas">
<a class="btn btn-cta" href={lienContribution} target="_blank" rel="noopener noreferrer">
{t().lacuneFr.cta}
</a>
<a class="lien-wikidata" href={lienWikidata} target="_blank" rel="noopener noreferrer">
{t().lacuneFr.ctaWikidata}
</a>
</div>
</article>
{:else}
<!-- Cas B : lacune documentaire — panneau volontairement distinct (Peak-End) -->
<article class="panneau cas-b">
<h2><span class="icone" aria-hidden="true"></span> {t().lacune.titre}</h2>
<p class="texte">{t().lacune.texte}</p>
<a class="btn btn-cta" href={lienContribution} target="_blank" rel="noopener noreferrer">
{t().lacune.cta}
</a>
<p class="guide">
{t().lacune.guide}
<a href="https://fr.wikipedia.org/wiki/Aide:Premiers_pas" target="_blank" rel="noopener noreferrer">
{t().lacune.guideLien}
</a>
</p>
</article>
{/if}
<style>
.panneau {
border-radius: var(--oki-radius);
padding: 1.1rem 1.25rem;
box-shadow: var(--oki-ombre);
}
.chargement {
background: var(--oki-blanc);
color: var(--oki-encre-doux);
text-align: center;
}
/* Cas A : vert doux, apaisé */
.cas-a {
background: var(--oki-vert-doux);
border: 1.5px solid var(--oki-vert-clair);
}
.cas-a h2 {
margin: 0 0 0.3rem;
font-size: 1.2rem;
}
.cas-a h2 a {
color: var(--oki-vert);
}
.cas-a .ton {
margin: 0 0 0.6rem;
font-weight: 600;
color: var(--oki-vert-clair);
}
.cas-a img {
float: right;
width: 96px;
height: auto;
margin: 0 0 0.5rem 0.8rem;
border-radius: var(--oki-radius-petit);
}
.cas-a .extrait {
margin: 0 0 0.6rem;
}
.lien-wiki {
color: var(--oki-bleu);
font-weight: 650;
}
/* Cas B : teinte sable/orangée distincte, icône spécifique */
.cas-b {
background: var(--oki-lacune-fond);
border: 2px solid var(--oki-lacune-bord);
}
.cas-b h2 {
margin: 0 0 0.5rem;
font-size: 1.25rem;
color: #8a5a00;
display: flex;
align-items: center;
gap: 0.5rem;
}
.cas-b .icone {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.6rem;
height: 1.6rem;
border: 2.5px dashed var(--oki-lacune-bord);
border-radius: 50%;
font-size: 1rem;
}
.cas-b .texte {
margin: 0 0 0.9rem;
font-size: 1.02rem;
}
.btn-cta {
background: var(--oki-lacune-bord);
color: #fff;
}
.btn-cta:hover {
background: #b98a2f;
}
.ctas {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.9rem;
}
.lien-wikidata {
color: var(--oki-bleu);
font-weight: 650;
}
.guide {
margin: 0.8rem 0 0;
font-size: 0.88rem;
color: var(--oki-encre-doux);
}
.guide a {
color: var(--oki-bleu);
font-weight: 600;
}
</style>
+128
View File
@@ -0,0 +1,128 @@
const fr = {
app: {
titre: 'JWE',
sousTitre: 'Jeu de géolocalisation — Guadeloupe, Martinique, Guyane, La Réunion'
},
regions: {
GUADELOUPE: 'Guadeloupe',
MARTINIQUE: 'Martinique',
GUYANE: 'Guyane',
REUNION: 'La Réunion',
TOUTES: 'Toutes les régions'
},
modes: {
monument: 'Konnèt moniman',
monumentDesc: 'Reconnais le monument photographié et place-le sur la carte.',
lieu: 'Kote mwen ye ?',
lieuDesc: 'Une rue, un bord de mer, une forêt… devine où tu es.',
defi: 'Défi 5 rounds',
defiDesc: '5 lieux daffilée, monuments et lieux mélangés.',
street: 'An lari a',
streetDesc: 'Navigue dans une rue en photo 360° et devine la commune.',
explorer: 'Aprann',
explorerDesc: 'Explore la carte librement et lis les fiches Wikipédia. Sans score.'
},
accueil: {
choixRegion: 'Choisis ta région',
choixMode: 'Choisis ton mode',
options: 'Options',
timer: 'Minuteur (60 s, bonus de score)',
jouer: 'Jouer',
creerLienDefi: 'Créer un lien de défi'
},
jeu: {
charger: 'Chargement du lieu…',
erreur: 'Impossible de charger un lieu. Réessaie.',
reessayer: 'Réessayer',
valider: 'Valider ma position',
passer: 'Passer',
indice: 'Indice',
indicePenalite: '10 % de score',
indiceRestant: 'indice restant',
indicesRestants: 'indices restants',
plusDIndice: 'Plus dindice disponible',
poserMarqueur: 'Clique sur la carte pour placer ton marqueur',
streetChargement: 'Chargement de la vue de rue…',
streetErreur: 'Impossible de charger la photo Mapillary. Réessaie ou passe au lieu suivant.',
streetToken: 'Visionneuse indisponible : configuration Mapillary manquante.',
streetAriaLabel: 'Vue de rue interactive. Flèches pour avancer, glisser pour regarder autour.',
round: 'Manche',
sur: 'sur',
difficulte: {
FACILE: 'Facile',
MOYEN: 'Moyen',
DIFFICILE: 'Difficile',
EXPERT: 'Expert'
}
},
resultat: {
bravo: 'Bravo !',
score: 'Score',
points: 'points',
distance: 'Distance',
km: 'km',
trouve: 'Tu as trouvé ! Apprends-en plus sur ce lieu.',
aDecouvrir: 'Le lieu était ici. Apprends-en plus sur lui.',
lireWiki: 'Lire la suite sur Wikipédia',
rayonScore: 'Rayon de notation',
commune: 'Commune',
region: 'Région',
suivant: 'Lieu suivant',
voirBilan: 'Voir le bilan',
rejouer: 'Rejouer',
retourAccueil: 'Retour à laccueil'
},
lacune: {
titre: 'Pwen blindé — Sa pa dokimanté',
texte:
'Ce lieu existe, mais il na pas de page sur Wikipédia ni de fiche sur Wikidata. Pour nos régions, cest un enjeu majeur : si nous ne documentons pas nos propres territoires, notre histoire et notre géographie disparaissent des cartes numériques et des bases de données mondiales (qui alimentent même lintelligence artificielle).',
cta: 'Kontribyé sou Wikipédia',
guide: 'Besoin daide pour démarrer ? Suis le guide OKI « Comment contribuer à Wikipédia ».',
guideLien: 'Ouvrir le guide de contribution'
},
lacuneFr: {
titre: 'Pas encore darticle en français',
texte:
'La fiche Wikidata de ce lieu existe, mais personne na encore écrit larticle Wikipédia en français. Tu peux le traduire ou le créer : chaque article compte pour que nos territoires existent dans lencyclopédie francophone.',
cta: 'Traduire ou créer larticle',
ctaWikidata: 'Voir la fiche Wikidata'
},
defi: {
bilan: 'Bilan du défi',
scoreTotal: 'Score total',
partager: 'Partager',
telecharger: 'Télécharger limage',
taPosition: 'Ta position',
positionReelle: 'Position réelle',
manche: 'Manche',
titreSeed: 'Défi — seed',
copierLien: 'Copier le lien du défi',
lienCopie: 'Lien copié !'
},
explorer: {
titre: 'Aprann — Explorer',
filtrer: 'Filtrer par région',
chargerFiche: 'Chargement de la fiche…',
aucuneFiche: 'Sélectionne un marqueur sur la carte.',
fermer: 'Fermer le panneau'
},
carte: {
ariaLabel: 'Carte de jeu. Flèches pour déplacer le marqueur, Entrée pour valider.',
sautRegion: 'Aller à la région',
zoomIn: 'Zoomer',
zoomOut: 'Dézoomer',
carteRegionsLabel: 'Carte des quatre régions : Guadeloupe, Martinique, Guyane, La Réunion'
},
micro: {
bravo: 'Bravo !',
kiteSaYe: 'Kité sa ye ?',
pwenBlinde: 'Pwen blindé'
},
langue: {
fr: 'Français',
gcf: 'Kreyòl'
}
};
export default fr;
export type Dict = typeof fr;
+129
View File
@@ -0,0 +1,129 @@
import type { Dict } from './fr';
const gcf: Dict = {
app: {
titre: 'JWE',
sousTitre: 'Jwé jéyolokalizasyon — Gwadloup, Matinik, Giyan, Léryinyon'
},
regions: {
GUADELOUPE: 'Gwadloup',
MARTINIQUE: 'Matinik',
GUYANE: 'Giyan',
REUNION: 'Léryinyon',
TOUTES: 'Tout péyi yo'
},
modes: {
monument: 'Konnèt moniman',
monumentDesc: 'Roukonèt moniman-an asou foto-a é mété’y asou kat-la.',
lieu: 'Kote mwen ye ?',
lieuDesc: 'On lari, on bodlanmè, on fowé… chwé kote ou yé.',
defi: 'Défi 5 rounds',
defiDesc: '5 koté youn dèyè ròt, moniman épi plas mélanjé.',
street: 'An lari a',
streetDesc: 'Mache nan on lari an foto 360° é chwé komin-lan.',
explorer: 'Aprann',
explorerDesc: 'Flanné asou kat-la é li fich Wikipédia yo. San pwen.'
},
accueil: {
choixRegion: 'Chwazi péyi ou',
choixMode: 'Chwazi jan ou vlé jwé',
options: 'Règlaj',
timer: 'Kronomèt (60 s, bonus pwen)',
jouer: 'Jwé',
creerLienDefi: 'Réyé on lyen défi'
},
jeu: {
charger: 'Nou ka chajé koté-la…',
erreur: 'Nou pa rivé chajé on koté. Éséyé ankò.',
reessayer: 'Éséyé ankò',
valider: 'Validé pozisyon mwen',
passer: 'Pasé',
indice: 'Endis',
indicePenalite: '10 % pwen',
indiceRestant: 'endis ki rété',
indicesRestants: 'endis ki rété',
plusDIndice: 'Pa ni endis ankò',
poserMarqueur: 'Kwiké asou kat-la pou mété makò-a',
streetChargement: 'Nou ka chajé vi lari-a…',
streetErreur: 'Nou pa rivé chajé foto Mapillary-la. Éséyé ankò oben pasé o koté swivan.',
streetToken: 'Vi lari-a pa disponib : konfigirasyon Mapillary-la manké.',
streetAriaLabel: 'Vi lari-a. Flèch yo pou avansé, glissé pou gadté toutò.',
round: 'Mannèk',
sur: 'asou',
difficulte: {
FACILE: 'Fasil',
MOYEN: 'Mwayen',
DIFFICILE: 'Difisil',
EXPERT: 'Espè'
}
},
resultat: {
bravo: 'Bravo !',
score: 'Pwen',
points: 'pwen',
distance: 'Distans',
km: 'km',
trouve: 'Ou trouvé ! Aprann pli plis asou koté sa-a.',
aDecouvrir: 'Koté-la té la. Aprann pli plis asouy.',
lireWiki: 'Li swit-la asou Wikipédia',
rayonScore: 'Réyon pou pwen yo',
commune: 'Komin',
region: 'Péyi',
suivant: 'Koté swivan',
voirBilan: 'Wè bilan-an',
rejouer: 'Rèjwé',
retourAccueil: 'Tounen an lakay'
},
lacune: {
titre: 'Pwen blindé — Sa pa dokimanté',
texte:
'Koté sa-a égzisté, men i pa ni on paj asou Wikipédia ni on fich asou Wikidata. Pou péyi nou, sé on zafè enpòtan anpil : si nou pa dokimanté pwòp téritwa nou, listwa épi jéwografi nou kay disparèt asou kat nimérik épi labaz donné lemonn yo (ki manm ka bay manjé a lintelijans atifisyèl).',
cta: 'Kontribyé sou Wikipédia',
guide: 'Ou bizwen èd pou koumansé ? Swiv gid OKI « Kijan pou kontribyé sou Wikipédia ».',
guideLien: 'Ouvri gid kontribisyon-an'
},
lacuneFr: {
titre: 'Pwen blindé — Pa nyen an fransé',
texte:
'Fich Wikidata koté sa-a égzisté, mé pésonn pòkò ékri atik Wikipédia-la an fransé. Ou sa tradwiy oben réyé’y : chak atik ka konté pou téritwa nou égzisté adan ansiklopedi fransé-a.',
cta: 'Tradwi oben réyé atik-la',
ctaWikidata: 'Wè fich Wikidata-la'
},
defi: {
bilan: 'Bilan défi-a',
scoreTotal: 'Total pwen',
partager: 'Palé di moun',
telecharger: 'Téléchajé foto-a',
taPosition: 'Pozisyon ou',
positionReelle: 'Rèl pozisyon-an',
manche: 'Mannèk',
titreSeed: 'Défi — seed',
copierLien: 'Kopié lyen défi-a',
lienCopie: 'Lyen kopié !'
},
explorer: {
titre: 'Aprann — Flanné',
filtrer: 'Triyé pa péyi',
chargerFiche: 'Nou ka chajé fich-la…',
aucuneFiche: 'Kwiké asou on makò asou kat-la.',
fermer: 'Fèmé pano-a'
},
carte: {
ariaLabel: 'Kat jwé-a. Flèch yo pou déplasé makò-a, Antré pou validé.',
sautRegion: 'Alé o péyi',
zoomIn: 'Zoumé',
zoomOut: 'Dézoumé',
carteRegionsLabel: 'Kat 4 péyi yo : Gwadloup, Matinik, Giyan, Léryinyon'
},
micro: {
bravo: 'Bravo !',
kiteSaYe: 'Kité sa ye ?',
pwenBlinde: 'Pwen blindé'
},
langue: {
fr: 'Français',
gcf: 'Kreyòl'
}
};
export default gcf;
+38
View File
@@ -0,0 +1,38 @@
import { browser } from '$app/environment';
import fr, { type Dict } from './fr';
import gcf from './gcf';
export type Lang = 'fr' | 'gcf';
const dicts: Record<Lang, Dict> = { fr, gcf };
const STORAGE_KEY = 'jwe-lang';
let lang = $state<Lang>('fr');
/** Dictionnaire courant — fonction réactive : lit le `$state`, donc les templates se mettent à jour. */
export function t(): Dict {
return dicts[lang];
}
export function getLang(): Lang {
return lang;
}
export function setLang(next: Lang): void {
lang = next;
if (browser) {
localStorage.setItem(STORAGE_KEY, next);
document.documentElement.lang = next;
}
}
/** À appeler une fois au montage du layout : restaure la langue persistée. */
export function initLang(): void {
if (!browser) return;
const saved = localStorage.getItem(STORAGE_KEY);
if (saved === 'fr' || saved === 'gcf') {
setLang(saved);
} else {
document.documentElement.lang = lang;
}
}
File diff suppressed because one or more lines are too long
+16
View File
@@ -0,0 +1,16 @@
import type { Region } from '$lib/types';
/** Bornes de chaque région : [lonOuest, latSud, lonEst, latNord]. */
export const REGION_BOUNDS: Record<Region, [number, number, number, number]> = {
GUADELOUPE: [-61.9, 15.8, -60.95, 16.55],
MARTINIQUE: [-61.25, 14.35, -60.75, 14.95],
GUYANE: [-54.7, 1.9, -51.5, 6.0],
REUNION: [55.15, -21.42, 55.9, -20.82]
};
/** Enveloppe union des 4 régions (≈ lon 63…57, lat 23…18) : interdit de sortir du terrain de jeu. */
export const MAX_BOUNDS: [number, number, number, number] = [-63, -23, 57, 18];
export const MIN_ZOOM = 4;
export const REGIONS: Region[] = ['GUADELOUPE', 'MARTINIQUE', 'GUYANE', 'REUNION'];
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+602
View File
@@ -0,0 +1,602 @@
[
{
"id": "st-01",
"nom": "Rue Laurence Valmy, Pointe-à-Pitre",
"nom_creole": "Lari Pointe-à-Pitre",
"region": "GUADELOUPE",
"commune": "Pointe-à-Pitre",
"coordonnees": {
"lat": 16.244455939903,
"lon": -61.530342688698
},
"difficulte": "MOYEN",
"mapillary_id": "2941939632687980",
"credit": {
"username": "cartophyl",
"captured_at": "2015-07-07"
},
"is_pano": false,
"wikidata_id": "Q335322",
"indices": [
{
"niveau": 1,
"texte": "Île papillon, aile droite"
},
{
"niveau": 2,
"texte": "Port de commerce principal de larchipel"
}
],
"aire_commune_km2": 2.78
},
{
"id": "st-02",
"nom": "Rue Achille René Boisneuf, Les Abymes",
"nom_creole": "Lari Les Abymes",
"region": "GUADELOUPE",
"commune": "Les Abymes",
"coordonnees": {
"lat": 16.269078645766,
"lon": -61.506631441162
},
"difficulte": "MOYEN",
"mapillary_id": "306781020957650",
"credit": {
"username": "ratzillas",
"captured_at": "2015-07-17"
},
"is_pano": false,
"wikidata_id": "Q13636",
"indices": [
{
"niveau": 1,
"texte": "Île papillon, aile droite"
},
{
"niveau": 2,
"texte": "Commune la plus peuplée de larchipel"
}
],
"aire_commune_km2": 70.43
},
{
"id": "st-03",
"nom": "Place Renovation le Bourg, Le Gosier",
"nom_creole": "Lari Le Gosier",
"region": "GUADELOUPE",
"commune": "Le Gosier",
"coordonnees": {
"lat": 16.205608856053,
"lon": -61.492154911837
},
"difficulte": "DIFFICILE",
"mapillary_id": "919062132219342",
"credit": {
"username": "kaartcam",
"captured_at": "2016-01-02"
},
"is_pano": false,
"wikidata_id": "Q918874",
"indices": [
{
"niveau": 1,
"texte": "Île papillon, aile droite"
},
{
"niveau": 2,
"texte": "Station balnéaire au sud de la Grande-Terre"
}
],
"aire_commune_km2": 45.75
},
{
"id": "st-04",
"nom": "Rue Emmanuel Robinet, Sainte-Anne",
"nom_creole": "Lari Sainte-Anne",
"region": "GUADELOUPE",
"commune": "Sainte-Anne",
"coordonnees": {
"lat": 16.223896372356,
"lon": -61.384172350192
},
"difficulte": "DIFFICILE",
"mapillary_id": "956408765176680",
"credit": {
"username": "ratzillas",
"captured_at": "2019-07-15"
},
"is_pano": true,
"wikidata_id": "Q386243",
"indices": [
{
"niveau": 1,
"texte": "Île papillon, aile droite"
},
{
"niveau": 2,
"texte": "Plages au sud de la Grande-Terre"
}
],
"aire_commune_km2": 80.96
},
{
"id": "st-05",
"nom": "Route des Esclaves, Basse-Terre",
"nom_creole": "Lari Basse-Terre",
"region": "GUADELOUPE",
"commune": "Basse-Terre",
"coordonnees": {
"lat": 15.992959593433,
"lon": -61.730437544596
},
"difficulte": "EXPERT",
"mapillary_id": "212605717097536",
"credit": {
"username": "kaartcam",
"captured_at": "2016-01-04"
},
"is_pano": false,
"wikidata_id": "Q167024",
"indices": [
{
"niveau": 1,
"texte": "Île papillon, aile gauche"
},
{
"niveau": 2,
"texte": "Chef-lieu au pied du volcan"
}
],
"aire_commune_km2": 4.5
},
{
"id": "st-06",
"nom": "Rue Victor Sévère, Fort-de-France",
"nom_creole": "Lari Fort-de-France",
"region": "MARTINIQUE",
"commune": "Fort-de-France",
"coordonnees": {
"lat": 14.60615582786,
"lon": -61.069885806689
},
"difficulte": "MOYEN",
"mapillary_id": "152801196814796",
"credit": {
"username": "kaartcam",
"captured_at": "2015-12-31"
},
"is_pano": false,
"wikidata_id": "Q81621",
"indices": [
{
"niveau": 1,
"texte": "Île aux fleurs"
},
{
"niveau": 2,
"texte": "Chef-lieu, sur une grande baie"
}
],
"aire_commune_km2": 44.04
},
{
"id": "st-07",
"nom": "Rue des Barrières, Le Lamentin",
"nom_creole": "Lari Le Lamentin",
"region": "MARTINIQUE",
"commune": "Le Lamentin",
"coordonnees": {
"lat": 14.615969225175,
"lon": -60.999773265489
},
"difficulte": "MOYEN",
"mapillary_id": "1120779875836768",
"credit": {
"username": "Caramel",
"captured_at": "2024-04-29"
},
"is_pano": true,
"wikidata_id": "Q947069",
"indices": [
{
"niveau": 1,
"texte": "Île aux fleurs"
},
{
"niveau": 2,
"texte": "Banlieue du chef-lieu, zone aéroportuaire"
}
],
"aire_commune_km2": 62.73
},
{
"id": "st-08",
"nom": "Rue Gabriel Péri, Saint-Pierre",
"nom_creole": "Lari Saint-Pierre",
"region": "MARTINIQUE",
"commune": "Saint-Pierre",
"coordonnees": {
"lat": 14.738699893002,
"lon": -61.176412948112
},
"difficulte": "DIFFICILE",
"mapillary_id": "1299527321706804",
"credit": {
"username": "jeremylavarenne",
"captured_at": "2025-08-31"
},
"is_pano": false,
"wikidata_id": "Q589980",
"indices": [
{
"niveau": 1,
"texte": "Île aux fleurs, côte caraïbe nord"
},
{
"niveau": 2,
"texte": "Ville détruite par une éruption en 1902"
}
],
"aire_commune_km2": 38.69
},
{
"id": "st-09",
"nom": "Rue Florent Holo, Le François",
"nom_creole": "Lari Le François",
"region": "MARTINIQUE",
"commune": "Le François",
"coordonnees": {
"lat": 14.615696752255,
"lon": -60.902520891662
},
"difficulte": "DIFFICILE",
"mapillary_id": "4102521129805870",
"credit": {
"username": "kaartcam",
"captured_at": "2016-01-01"
},
"is_pano": false,
"wikidata_id": "Q282944",
"indices": [
{
"niveau": 1,
"texte": "Île aux fleurs, côte atlantique"
},
{
"niveau": 2,
"texte": "Bourg face aux îlets du sud"
}
],
"aire_commune_km2": 54.43
},
{
"id": "st-10",
"nom": "Passage des Fleurs, Sainte-Marie",
"nom_creole": "Lari Sainte-Marie",
"region": "MARTINIQUE",
"commune": "Sainte-Marie",
"coordonnees": {
"lat": 14.783766654906,
"lon": -60.995666311379
},
"difficulte": "EXPERT",
"mapillary_id": "131479329019761",
"credit": {
"username": "kaartcam",
"captured_at": "2015-12-31"
},
"is_pano": false,
"wikidata_id": "Q1758414",
"indices": [
{
"niveau": 1,
"texte": "Île aux fleurs, côte atlantique nord"
},
{
"niveau": 2,
"texte": "Musée de la banane et rhum"
}
],
"aire_commune_km2": 44.65
},
{
"id": "st-11",
"nom": "Rue Francois Arago, Cayenne",
"nom_creole": "Lari Cayenne",
"region": "GUYANE",
"commune": "Cayenne",
"coordonnees": {
"lat": 4.9388185867966,
"lon": -52.331808101487
},
"difficulte": "MOYEN",
"mapillary_id": "259270559222687",
"credit": {
"username": "kaartcam",
"captured_at": "2016-08-18"
},
"is_pano": false,
"wikidata_id": "Q44401",
"indices": [
{
"niveau": 1,
"texte": "Terre de forêt amazonienne"
},
{
"niveau": 2,
"texte": "Chef-lieu, sur l’île du même nom"
}
],
"aire_commune_km2": 25.52
},
{
"id": "st-12",
"nom": "Rue de lOdéon, Kourou",
"nom_creole": "Lari Kourou",
"region": "GUYANE",
"commune": "Kourou",
"coordonnees": {
"lat": 5.1615176393394,
"lon": -52.643325658226
},
"difficulte": "DIFFICILE",
"mapillary_id": "198127629404270",
"credit": {
"username": "hacp",
"captured_at": "2022-09-07"
},
"is_pano": false,
"wikidata_id": "Q273312",
"indices": [
{
"niveau": 1,
"texte": "Terre de forêt amazonienne"
},
{
"niveau": 2,
"texte": "Ville des fusées"
}
],
"aire_commune_km2": 2289.2
},
{
"id": "st-13",
"nom": "Avenue Albert Sarraut, Saint-Laurent-du-Maroni",
"nom_creole": "Lari Saint-Laurent-du-Maroni",
"region": "GUYANE",
"commune": "Saint-Laurent-du-Maroni",
"coordonnees": {
"lat": 5.5060375294565,
"lon": -54.027135700884
},
"difficulte": "DIFFICILE",
"mapillary_id": "147142287390967",
"credit": {
"username": "pma",
"captured_at": "2021-01-18"
},
"is_pano": false,
"wikidata_id": "Q319959",
"indices": [
{
"niveau": 1,
"texte": "Terre de forêt amazonienne, à louest"
},
{
"niveau": 2,
"texte": "Ville du fleuve Maroni, ancien bagne"
}
],
"aire_commune_km2": 4320.77
},
{
"id": "st-14",
"nom": "Rue Maurice BOCS, Matoury",
"nom_creole": "Lari Matoury",
"region": "GUYANE",
"commune": "Matoury",
"coordonnees": {
"lat": 4.8496318387901,
"lon": -52.328783153736
},
"difficulte": "EXPERT",
"mapillary_id": "582210316504280",
"credit": {
"username": "kaartcam",
"captured_at": "2016-08-18"
},
"is_pano": false,
"wikidata_id": "Q816739",
"indices": [
{
"niveau": 1,
"texte": "Terre de forêt amazonienne"
},
{
"niveau": 2,
"texte": "Banlieue sud du chef-lieu"
}
],
"aire_commune_km2": 146.68
},
{
"id": "st-15",
"nom": "Rue de la CANNE À SUCRE, Remire-Montjoly",
"nom_creole": "Lari Remire-Montjoly",
"region": "GUYANE",
"commune": "Remire-Montjoly",
"coordonnees": {
"lat": 4.9037937340773,
"lon": -52.273335996076
},
"difficulte": "EXPERT",
"mapillary_id": "247810083801809",
"credit": {
"username": "kaartcam",
"captured_at": "2016-08-18"
},
"is_pano": false,
"wikidata_id": "Q996222",
"indices": [
{
"niveau": 1,
"texte": "Terre de forêt amazonienne"
},
{
"niveau": 2,
"texte": "Plages à lest du chef-lieu"
}
],
"aire_commune_km2": 46.3
},
{
"id": "st-16",
"nom": "Rue de Paris, Saint-Denis",
"nom_creole": "Lari Saint-Denis",
"region": "REUNION",
"commune": "Saint-Denis",
"coordonnees": {
"lat": -20.8832861,
"lon": 55.4501
},
"difficulte": "MOYEN",
"mapillary_id": "2262788723930767",
"credit": {
"username": "AllWays360",
"captured_at": "2022-10-06"
},
"is_pano": true,
"wikidata_id": "Q47045",
"indices": [
{
"niveau": 1,
"texte": "Île intense de locéan Indien"
},
{
"niveau": 2,
"texte": "Chef-lieu, au nord"
}
],
"aire_commune_km2": 142.33
},
{
"id": "st-17",
"nom": "Rue du Cimetiere, Saint-Pierre",
"nom_creole": "Lari Saint-Pierre",
"region": "REUNION",
"commune": "Saint-Pierre",
"coordonnees": {
"lat": -21.338988428747,
"lon": 55.478221620359
},
"difficulte": "MOYEN",
"mapillary_id": "143202321798356",
"credit": {
"username": "sigstpierre",
"captured_at": "2022-11-09"
},
"is_pano": true,
"wikidata_id": "Q249884",
"indices": [
{
"niveau": 1,
"texte": "Île intense de locéan Indien"
},
{
"niveau": 2,
"texte": "Capitale du sud, front de mer animé"
}
],
"aire_commune_km2": 96.82
},
{
"id": "st-18",
"nom": "Rue Aristide Briand, Le Tampon",
"nom_creole": "Lari Le Tampon",
"region": "REUNION",
"commune": "Le Tampon",
"coordonnees": {
"lat": -21.277675635385,
"lon": 55.514338556402
},
"difficulte": "DIFFICILE",
"mapillary_id": "1382811445417165",
"credit": {
"username": "vandecasteele",
"captured_at": "2019-12-16"
},
"is_pano": false,
"wikidata_id": "Q13648",
"indices": [
{
"niveau": 1,
"texte": "Île intense de locéan Indien"
},
{
"niveau": 2,
"texte": "Commune des hauts, dans le sud"
}
],
"aire_commune_km2": 182.09
},
{
"id": "st-19",
"nom": "Rue Elie Eudor, Saint-Paul",
"nom_creole": "Lari Saint-Paul",
"region": "REUNION",
"commune": "Saint-Paul",
"coordonnees": {
"lat": -21.008621906549,
"lon": 55.271355918998
},
"difficulte": "DIFFICILE",
"mapillary_id": "928324514646684",
"credit": {
"username": "sogefi",
"captured_at": "2018-10-14"
},
"is_pano": false,
"wikidata_id": "Q316887",
"indices": [
{
"niveau": 1,
"texte": "Île intense de locéan Indien"
},
{
"niveau": 2,
"texte": "Côte ouest, premier site de peuplement"
}
],
"aire_commune_km2": 241.64
},
{
"id": "st-20",
"nom": "Ccal de la Republique, Saint-André",
"nom_creole": "Lari Saint-André",
"region": "REUNION",
"commune": "Saint-André",
"coordonnees": {
"lat": -20.962268395233,
"lon": 55.651364657007
},
"difficulte": "EXPERT",
"mapillary_id": "519625869420978",
"credit": {
"username": "vandecasteele",
"captured_at": "2019-06-28"
},
"is_pano": true,
"wikidata_id": "Q1649370",
"indices": [
{
"niveau": 1,
"texte": "Île intense de locéan Indien"
},
{
"niveau": 2,
"texte": "Côte est, pays de la canne"
}
],
"aire_commune_km2": 54.66
}
]
+247
View File
@@ -0,0 +1,247 @@
import rawLieux from './data/lieux.json';
import rawStreet from './data/street.json';
import type {
Categorie,
Difficulte,
ExplorerLieu,
GuessResult,
Lieu,
Region,
RoundPlace,
StreetLieu
} from '$lib/types';
const lieux = rawLieux as Lieu[];
const street = rawStreet as StreetLieu[];
/** Lieu « scorable » : les deux corpus partagent les champs du scoring. */
type Scoreable = Lieu | StreetLieu;
const REGIONS: Region[] = ['GUADELOUPE', 'MARTINIQUE', 'GUYANE', 'REUNION'];
const CATEGORIES: Categorie[] = ['MONUMENT', 'LIEU'];
export const MAX_POINTS = 5000;
/** Rayon (km) de la courbe de score selon la difficulté du lieu. */
export const RAYONS: Record<Difficulte, number> = {
FACILE: 50,
MOYEN: 15,
DIFFICILE: 5,
EXPERT: 1
};
/** Distance haversine en km. */
export function haversineKm(a: { lat: number; lon: number }, b: { lat: number; lon: number }): number {
const R = 6371;
const dLat = ((b.lat - a.lat) * Math.PI) / 180;
const dLon = ((b.lon - a.lon) * Math.PI) / 180;
const s =
Math.sin(dLat / 2) ** 2 +
Math.cos((a.lat * Math.PI) / 180) * Math.cos((b.lat * Math.PI) / 180) * Math.sin(dLon / 2) ** 2;
return 2 * R * Math.asin(Math.sqrt(s));
}
function parseRegion(value: string | null): Region | null {
return value && REGIONS.includes(value as Region) ? (value as Region) : null;
}
function parseCategorie(value: string | null): Categorie | null {
return value && CATEGORIES.includes(value as Categorie) ? (value as Categorie) : null;
}
/** Recherche dans les deux corpus (photos classiques + street Mapillary). */
export function getLieuById(id: string): Scoreable | undefined {
return lieux.find((l) => l.id === id) ?? street.find((l) => l.id === id);
}
/** Recherche limitée au corpus photo classique (défi, proxy photo). */
export function getLieuPhotoById(id: string): Lieu | undefined {
return lieux.find((l) => l.id === id);
}
/** Sélection aléatoire d'un lieu, avec filtres optionnels. */
export function getRandomLieu(options: {
region?: string | null;
categorie?: string | null;
exclude?: string | null;
}): Lieu | null {
const region = parseRegion(options.region ?? null);
const categorie = parseCategorie(options.categorie ?? null);
const excluded = new Set(
(options.exclude ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
);
let pool = lieux.filter((l) => !excluded.has(l.id));
if (region) pool = pool.filter((l) => l.region === region);
if (categorie) pool = pool.filter((l) => l.categorie === categorie);
// Si tout a été exclu, on réessaie sans les exclusions (le jeu doit continuer).
if (pool.length === 0) {
pool = lieux;
if (region) pool = pool.filter((l) => l.region === region);
if (categorie) pool = pool.filter((l) => l.categorie === categorie);
}
if (pool.length === 0) return null;
return pool[Math.floor(Math.random() * pool.length)];
}
/** Sélection aléatoire d'un lieu street (mode « An lari a », corpus Mapillary). */
export function getRandomStreet(options: {
region?: string | null;
exclude?: string | null;
}): StreetLieu | null {
const region = parseRegion(options.region ?? null);
const excluded = new Set(
(options.exclude ?? '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
);
let pool = street.filter((l) => !excluded.has(l.id));
if (region) pool = pool.filter((l) => l.region === region);
// Si tout a été exclu, on réessaie sans les exclusions (le jeu doit continuer).
if (pool.length === 0) {
pool = region ? street.filter((l) => l.region === region) : street;
}
if (pool.length === 0) return null;
return pool[Math.floor(Math.random() * pool.length)];
}
/** Largeurs (px) servies par le proxy photo /api/photo/[id]?w=. */
export const PHOTO_LARGEURS = [400, 800, 1200] as const;
/**
* Anti-triche : ne garde que les champs publiques pour /api/round.
* L'URL photo passe par le proxy serveur (/api/photo/<uuid>) : l'URL Wikimedia
* Commons d'origine contient le nom du fichier, qui révèle souvent le lieu (C4).
*/
export function sanitizeRound(lieu: Lieu): RoundPlace {
return {
id: lieu.id,
nom: lieu.nom,
nom_creole: lieu.nom_creole,
categorie: lieu.categorie,
difficulte: lieu.difficulte,
photo: {
url: `/api/photo/${lieu.id}`,
srcset: {
'400': `/api/photo/${lieu.id}?w=400`,
'800': `/api/photo/${lieu.id}?w=800`,
'1200': `/api/photo/${lieu.id}?w=1200`
},
credit: lieu.photo.credit,
alt: lieu.photo.alt
},
indices: lieu.indices
};
}
/**
* Anti-triche, mode street : ne garde que les champs publics.
* Seul `mapillaryId` part au client (la visionneuse doit bien appeler Mapillary) ;
* coords/commune/région/wikidata_id ne partent jamais avant le guess.
* Limitation documentée (architecture.md §10) : l'image_key est publique côté
* Mapillary, un joueur techniquement équipé peut retrouver la position — même
* propriété que GeoGuessr/Street View, acceptable en solo sans leaderboard.
*/
export function sanitizeRoundStreet(lieu: StreetLieu): RoundPlace {
return {
id: lieu.id,
nom: lieu.nom,
nom_creole: lieu.nom_creole,
categorie: 'LIEU',
difficulte: lieu.difficulte,
mapillaryId: lieu.mapillary_id,
credit: `© ${lieu.credit.username} / Mapillary (CC BY-SA 4.0)`,
indices: lieu.indices
};
}
/**
* Rayon effectif (km) de la courbe de score (audit A1).
* Les communes guyanaises sont immenses (Saint-Laurent-du-Maroni ≈ 4 321 km²) :
* avec le seul rayon de difficulté, un guess à quelques dizaines de km y est
* injustement quasi nul. Quand `aire_commune_km2` est renseigné, le rayon est
* au moins celui du disque de même aire que la commune : sqrt(aire / π).
* Champ optionnel : sans lui, on retombe sur le rayon de difficulté.
*/
export function rayonEffectifKm(lieu: Scoreable): number {
const base = RAYONS[lieu.difficulte];
const aire = lieu.aire_commune_km2;
if (typeof aire === 'number' && Number.isFinite(aire) && aire > 0) {
return Math.max(base, Math.sqrt(aire / Math.PI));
}
return base;
}
/**
* Scoring recalculé côté serveur :
* score = round(5000 × e^(d/r_eff)) ; pénalité 10 % par indice ;
* bonus temps ≤ +20 % ; total plafonné à 5000.
*/
export function scoreGuess(
lieu: Scoreable,
guess: { lat: number; lon: number },
hintsUsed: number,
timeMs?: number
): GuessResult {
const distanceKm = haversineKm(guess, lieu.coordonnees);
const radiusEff = rayonEffectifKm(lieu);
const base = Math.round(MAX_POINTS * Math.exp(-distanceKm / radiusEff));
const penalises = base * Math.max(0, 1 - 0.1 * Math.max(0, hintsUsed));
let total = penalises;
if (typeof timeMs === 'number' && Number.isFinite(timeMs) && timeMs >= 0) {
total += penalises * 0.2 * Math.max(0, 1 - timeMs / 60000);
}
const score = Math.min(MAX_POINTS, Math.round(total));
return {
distanceKm: Math.round(distanceKm * 10) / 10,
score,
radiusEffKm: Math.round(radiusEff * 10) / 10,
coordonnees: lieu.coordonnees,
commune: lieu.commune,
region: lieu.region,
nom: lieu.nom,
nom_creole: lieu.nom_creole,
wikidata_id: lieu.wikidata_id
};
}
/** Réponse « Passer » : la vérité est révélée, score 0, pas de distance. */
export function skipResult(lieu: Scoreable): GuessResult {
return {
distanceKm: null,
score: 0,
radiusEffKm: null,
coordonnees: lieu.coordonnees,
commune: lieu.commune,
region: lieu.region,
nom: lieu.nom,
nom_creole: lieu.nom_creole,
wikidata_id: lieu.wikidata_id
};
}
/**
* Catalogue Explorer : coords arrondies à 0.05° (mode sans score, fiches autorisées).
* L'`id` (uuid) n'est volontairement PAS exposé : il permettrait de corréler
* l'id d'un round avec la commune du lieu (fuite de réponse, audit C4).
* L'Explorer n'a pas besoin d'ids stables (le front utilise l'indice du tableau).
*/
export function catalogueExplorer(): ExplorerLieu[] {
return lieux.map((l) => ({
nom: l.nom,
nom_creole: l.nom_creole,
region: l.region,
commune: l.commune,
coordonnees: {
lat: Math.round(l.coordonnees.lat / 0.05) * 0.05,
lon: Math.round(l.coordonnees.lon / 0.05) * 0.05
},
categorie: l.categorie,
difficulte: l.difficulte,
wikidata_id: l.wikidata_id,
photo: l.photo
}));
}
+86
View File
@@ -0,0 +1,86 @@
import rawLieux from './data/lieux.json';
import type { Categorie, Lieu } from '$lib/types';
const lieux = rawLieux as Lieu[];
/** Nombre de manches d'un défi. */
const NB_MANCHES = 5;
/** Seed acceptée : alphanumérique + tiret/underscore, 4 à 40 caractères. */
const SEED_REGEX = /^[A-Za-z0-9_-]{4,40}$/;
export function seedValide(seed: string): boolean {
return SEED_REGEX.test(seed);
}
/**
* Hash cyrb53 (domaine public) réduit à 32 bits.
* Arithmétique entière via Math.imul : résultat strictement identique sur
* toutes les plateformes — prérequis du déterminisme inter-machines (ADR-001 V1).
*/
function hashSeed(seed: string): number {
let h1 = 0xdeadbeef;
let h2 = 0x41c6ce57;
for (let i = 0; i < seed.length; i++) {
const ch = seed.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return (h1 ^ h2) >>> 0;
}
/** PRNG mulberry32 (domaine public) : flottants dans [0, 1), déterministes. */
function mulberry32(graine: number): () => number {
let a = graine;
return () => {
a |= 0;
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/**
* Tire les 5 lieux d'un défi à partir de la seed : mêmes lieux, même ordre,
* pour tous les joueurs et sur toutes les machines (ADR-001 v1).
* PRNG seedé exclusivement — jamais Math.random.
* Contraintes : ≥ 1 MONUMENT et ≥ 1 LIEU, et si possible ≥ 2 régions distinctes.
* Fonction pure : aucune I/O réseau, aucun état ; même entrée → même sortie.
*/
export function idsPourSeed(seed: string): string[] {
const rng = mulberry32(hashSeed(seed));
// Mélange de Fisher-Yates déterministe des indices du corpus.
const indices = lieux.map((_, i) => i);
for (let i = indices.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[indices[i], indices[j]] = [indices[j], indices[i]];
}
const melanges = indices.map((i) => lieux[i]);
const tires = melanges.slice(0, NB_MANCHES);
// ≥ 1 de chaque catégorie : si l'une manque, on échange un tiré contre le
// premier non-tiré de la catégorie manquante (l'autre catégorie reste présente).
const assurerCategorie = (categorie: Categorie): void => {
if (tires.some((l) => l.categorie === categorie)) return;
const candidat = melanges.find((l) => l.categorie === categorie && !tires.includes(l));
if (candidat) tires[0] = candidat;
};
assurerCategorie('MONUMENT');
assurerCategorie('LIEU');
// ≥ 2 régions distinctes si possible : on échange un tiré contre un non-tiré
// d'une autre région et de MÊME catégorie (contrainte catégories préservée,
// les deux étant présentes après l'étape précédente).
const regions = new Set(tires.map((l) => l.region));
if (regions.size < 2) {
const candidat = melanges.find((l) => !tires.includes(l) && !regions.has(l.region));
const i = candidat ? tires.findIndex((l) => l.categorie === candidat.categorie) : -1;
if (candidat && i >= 0) tires[i] = candidat;
}
return tires.map((l) => l.id);
}
+32
View File
@@ -0,0 +1,32 @@
import type { Coordonnees, GuessResult, RoundPlace } from '$lib/types';
export interface MancheDefi {
place: RoundPlace;
guess: Coordonnees | null;
result: GuessResult;
}
/** État du Défi 5 rounds — client uniquement, sans session serveur. */
function creerDefiStore() {
let manches = $state<MancheDefi[]>([]);
return {
get manches() {
return manches;
},
get total() {
return manches.reduce((s, m) => s + m.result.score, 0);
},
get termine() {
return manches.length >= 5;
},
ajouter(manche: MancheDefi) {
manches = [...manches, manche];
},
reinitialiser() {
manches = [];
}
};
}
export const defi = creerDefiStore();
+118
View File
@@ -0,0 +1,118 @@
/* Tokens OKI — doctrine « calm technology » : couleurs ancrées dans le territoire,
un seul accent fort (corail) réservé à l'action primaire (Von Restorff). */
:root {
--oki-vert: #0b3d2e; /* vert profond — couleur principale de la marque */
--oki-vert-clair: #17624a;
--oki-vert-doux: #e3efe7;
--oki-sable: #f5efe2; /* fonds */
--oki-sable-fonce: #e7dcc4;
--oki-bleu: #175e70; /* bleu caraïbe profond */
--oki-bleu-doux: #d9ecef;
--oki-corail: #e4572e; /* accent — action primaire UNIQUEMENT */
--oki-corail-fonce: #c4441f;
--oki-encre: #22302a;
--oki-encre-doux: #5a6b62;
--oki-blanc: #fffdf8;
--oki-lacune-fond: #fdf3e3; /* panneau Cas B « Pwen blindé » — teinte distincte */
--oki-lacune-bord: #d9a441;
--oki-radius: 14px;
--oki-radius-petit: 9px;
--oki-ombre: 0 2px 10px rgba(11, 61, 46, 0.14);
--oki-font:
system-ui,
-apple-system,
'Segoe UI',
Roboto,
sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
body {
font-family: var(--oki-font);
color: var(--oki-encre);
background: var(--oki-sable);
line-height: 1.5;
}
button {
font-family: inherit;
}
/* — Boutons — */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
border: none;
border-radius: var(--oki-radius-petit);
padding: 0.85rem 1.6rem;
font-size: 1.05rem;
font-weight: 650;
cursor: pointer;
text-decoration: none;
transition: background-color 0.15s ease;
}
.btn:focus-visible,
a:focus-visible,
[tabindex]:focus-visible {
outline: 3px solid var(--oki-bleu);
outline-offset: 2px;
}
/* Action primaire : le seul élément fortement coloré de l'écran */
.btn-primaire {
background: var(--oki-corail);
color: #fff;
box-shadow: var(--oki-ombre);
}
.btn-primaire:hover {
background: var(--oki-corail-fonce);
}
.btn-primaire:disabled {
background: var(--oki-sable-fonce);
color: var(--oki-encre-doux);
cursor: not-allowed;
box-shadow: none;
}
.btn-secondaire {
background: var(--oki-vert-doux);
color: var(--oki-vert);
}
.btn-secondaire:hover {
background: #d2e5d9;
}
.btn-tertiaire {
background: transparent;
color: var(--oki-vert-clair);
border: 1.5px solid var(--oki-vert-clair);
}
.btn-tertiaire:hover {
background: var(--oki-vert-doux);
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
transition-duration: 0.01ms !important;
animation-duration: 0.01ms !important;
}
}
+124
View File
@@ -0,0 +1,124 @@
export type Region = 'GUADELOUPE' | 'MARTINIQUE' | 'GUYANE' | 'REUNION';
export type Categorie = 'MONUMENT' | 'LIEU';
export type Difficulte = 'FACILE' | 'MOYEN' | 'DIFFICILE' | 'EXPERT';
export interface Coordonnees {
lat: number;
lon: number;
}
export interface Indice {
niveau: number;
texte: string;
}
export interface Photo {
url: string;
credit: string;
alt: string;
/**
* URLs par largeur (px) pour `srcset`. Présent uniquement dans /api/round :
* pointe vers le proxy /api/photo/[id]?w=… (l'URL Commons d'origine n'est jamais exposée).
*/
srcset?: Record<'400' | '800' | '1200', string>;
}
/** Lieu complet — serveur uniquement, jamais exposé tel quel au client. */
export interface Lieu {
id: string;
nom: string;
nom_creole: string;
region: Region;
commune: string;
coordonnees: Coordonnees;
categorie: Categorie;
difficulte: Difficulte;
wikidata_id: string | null;
photo: Photo;
indices: Indice[];
/**
* Superficie de la commune (km²) — champ optionnel du schéma.
* Sert à élargir le rayon de score pour les communes immenses (ex. Guyane) ;
* le scoring doit tolérer son absence (fallback = rayon de difficulté seul).
*/
aire_commune_km2?: number;
}
/**
* Lieu du mode street (« An lari a ») — serveur uniquement.
* La photo statique est remplacée par une image Mapillary (CC BY-SA 4.0).
* `wikidata_id` pointe vers la COMMUNE (phase éducative : fiche de la commune).
*/
export interface StreetLieu {
id: string;
nom: string;
nom_creole: string;
region: Region;
commune: string;
coordonnees: Coordonnees;
difficulte: Difficulte;
mapillary_id: string;
credit: { username: string; captured_at: string };
is_pano: boolean;
wikidata_id: string | null;
indices: Indice[];
aire_commune_km2?: number;
}
/** Lieu SANITISÉ envoyé par GET /api/round (aucune coordonnée, commune, région, wikidata_id). */
export interface RoundPlace {
id: string;
nom: string;
nom_creole: string;
categorie: Categorie;
difficulte: Difficulte;
/** Modes photo (monument/lieu/defi). Absent en mode street. */
photo?: Photo;
/** Mode street : identifiant d'image Mapillary à charger dans la visionneuse. */
mapillaryId?: string;
/** Crédit affiché au résultat en mode street (« © auteur / Mapillary (CC BY-SA 4.0) »). */
credit?: string;
indices: Indice[];
}
/** Réponse de POST /api/guess : la vérité n'est révélée qu'après soumission. */
export interface GuessResult {
distanceKm: number | null;
score: number;
/** Rayon effectif utilisé par la courbe de score (km, arrondi à 0,1) — null si « Passer ». */
radiusEffKm: number | null;
coordonnees: Coordonnees;
commune: string;
region: Region;
nom: string;
nom_creole: string;
wikidata_id: string | null;
}
/**
* Entrée du catalogue Explorer : coords arrondies à 0.05°, mode sans score.
* Pas d'`id` : exposer l'uuid du lieu permettrait de corréler l'id d'un round
* (/api/round) avec la commune/région — fuite de réponse (audit C4).
*/
export interface ExplorerLieu {
nom: string;
nom_creole: string;
region: Region;
commune: string;
coordonnees: Coordonnees;
categorie: Categorie;
difficulte: Difficulte;
wikidata_id: string | null;
photo: Photo;
}
/** Réponse normalisée de GET /api/wiki/[qid]. */
export interface WikiSummary {
qid: string;
title: string;
extract: string;
url: string;
thumbnail: string | null;
}
export type GameMode = 'monument' | 'lieu' | 'defi' | 'street';
+82
View File
@@ -0,0 +1,82 @@
<script lang="ts">
import { onMount } from 'svelte';
import '$lib/styles/oki.css';
import LangSwitch from '$lib/components/LangSwitch.svelte';
import { initLang, t } from '$lib/i18n/store.svelte';
let { children } = $props();
onMount(() => {
initLang();
});
</script>
<div class="app">
<header class="entete">
<a href="/" class="logo" aria-label="JWE — accueil">
<svg viewBox="0 0 32 32" width="30" height="30" aria-hidden="true">
<circle cx="16" cy="16" r="14" fill="none" stroke="currentColor" stroke-width="2.5" />
<path d="M16 7 L21 22 L16 18.5 L11 22 Z" fill="currentColor" />
</svg>
<span>{t().app.titre}</span>
</a>
<nav class="nav-lang">
<a href="/explorer" class="lien-explorer">{t().modes.explorer}</a>
<LangSwitch />
</nav>
</header>
<main>
{@render children()}
</main>
</div>
<style>
.app {
min-height: 100dvh;
display: flex;
flex-direction: column;
}
.entete {
display: flex;
align-items: center;
justify-content: space-between;
padding: 0.6rem 1rem;
background: var(--oki-vert);
color: #fff;
}
.logo {
display: inline-flex;
align-items: center;
gap: 0.5rem;
color: #fff;
text-decoration: none;
font-size: 1.4rem;
font-weight: 800;
letter-spacing: 0.04em;
}
.nav-lang {
display: flex;
align-items: center;
gap: 0.8rem;
}
.lien-explorer {
color: var(--oki-vert-doux);
text-decoration: none;
font-weight: 600;
font-size: 0.95rem;
}
.lien-explorer:hover {
color: #fff;
}
main {
flex: 1;
display: flex;
flex-direction: column;
}
</style>
+268
View File
@@ -0,0 +1,268 @@
<script lang="ts">
import { goto } from '$app/navigation';
import CarteRegions from '$lib/components/CarteRegions.svelte';
import { t } from '$lib/i18n/store.svelte';
import type { GameMode, Region } from '$lib/types';
type ChoixRegion = Region | 'TOUTES';
let region = $state<ChoixRegion>('TOUTES');
let mode = $state<GameMode>('monument');
let timer = $state(false);
const modes: { id: GameMode; emoji: string }[] = [
{ id: 'monument', emoji: '🏛️' },
{ id: 'lieu', emoji: '📍' },
{ id: 'defi', emoji: '⛰️' },
{ id: 'street', emoji: '🛣️' }
];
function jouer(): void {
const params = new URLSearchParams();
if (region !== 'TOUTES') params.set('region', region);
if (timer) params.set('timer', '1');
goto(`/jeu/${mode}${params.size ? `?${params}` : ''}`);
}
/** Génère une seed lisible (alphabet sans ambiguïté : pas de 0/O, 1/I/L) et ouvre le défi partagé. */
function creerLienDefi(): void {
const alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
const octets = new Uint8Array(8);
crypto.getRandomValues(octets);
const seed = Array.from(octets, (b) => alphabet[b % alphabet.length]).join('');
goto(`/defi/${seed}`);
}
</script>
<svelte:head>
<title>{t().app.titre}{t().app.sousTitre}</title>
<meta name="description" content={t().app.sousTitre} />
</svelte:head>
<div class="accueil">
<section class="hero">
<h1>{t().app.titre}</h1>
<p class="accroche">{t().micro.kiteSaYe}</p>
<p class="sous-titre">{t().app.sousTitre}</p>
</section>
<section aria-labelledby="titre-regions">
<h2 id="titre-regions">{t().accueil.choixRegion}</h2>
<div class="carte-accueil">
<CarteRegions bind:selection={region} />
<button
type="button"
class="btn btn-secondaire toutes"
class:choisi={region === 'TOUTES'}
aria-pressed={region === 'TOUTES'}
onclick={() => (region = 'TOUTES')}
>
{t().regions.TOUTES}
</button>
</div>
</section>
<section aria-labelledby="titre-modes">
<h2 id="titre-modes">{t().accueil.choixMode}</h2>
<div class="grille modes">
{#each modes as m (m.id)}
<button
type="button"
class="carte-mode"
class:choisi={mode === m.id}
aria-pressed={mode === m.id}
onclick={() => (mode = m.id)}
>
<span class="emoji" aria-hidden="true">{m.emoji}</span>
<span class="nom">{t().modes[m.id]}</span>
<span class="desc">{t().modes[`${m.id}Desc`]}</span>
</button>
{/each}
<a href="/explorer" class="carte-mode explorer">
<span class="emoji" aria-hidden="true">🧭</span>
<span class="nom">{t().modes.explorer}</span>
<span class="desc">{t().modes.explorerDesc}</span>
</a>
</div>
{#if mode === 'defi'}
<button type="button" class="btn btn-secondaire lien-defi" onclick={creerLienDefi}>
{t().accueil.creerLienDefi}
</button>
{/if}
</section>
<section class="options" aria-labelledby="titre-options">
<h2 id="titre-options">{t().accueil.options}</h2>
<label class="option-timer">
<input type="checkbox" bind:checked={timer} />
<span>{t().accueil.timer}</span>
</label>
</section>
<div class="zone-pouce">
<button type="button" class="btn btn-primaire jouer" onclick={jouer}>
{t().accueil.jouer}
</button>
</div>
</div>
<style>
.accueil {
width: 100%;
max-width: 860px;
margin: 0 auto;
padding: 1.25rem 1rem 7rem; /* espace pour le bouton fixe en zone pouce */
display: flex;
flex-direction: column;
gap: 1.6rem;
}
.hero {
text-align: center;
}
.hero h1 {
margin: 0;
font-size: 3rem;
font-weight: 800;
color: var(--oki-vert);
letter-spacing: 0.06em;
}
.accroche {
margin: 0.2rem 0 0;
font-size: 1.25rem;
font-weight: 650;
color: var(--oki-vert-clair);
font-style: italic;
}
.sous-titre {
margin: 0.4rem 0 0;
color: var(--oki-encre-doux);
}
h2 {
font-size: 1.05rem;
color: var(--oki-vert);
margin: 0 0 0.6rem;
}
.grille {
display: grid;
gap: 0.7rem;
}
.modes {
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
}
/* Carte SVG des régions + bouton « Toutes les régions » */
.carte-accueil {
max-width: 560px;
margin: 0 auto;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.6rem;
}
.toutes {
border: 2px solid transparent;
}
.toutes.choisi {
border-color: var(--oki-vert);
background: var(--oki-vert-doux);
}
/* Bouton secondaire « Créer un lien de défi », sous la grille des modes */
.lien-defi {
display: block;
margin: 0.8rem auto 0;
}
.carte-mode {
border: 2px solid transparent;
border-radius: var(--oki-radius);
background: var(--oki-blanc);
box-shadow: var(--oki-ombre);
cursor: pointer;
text-align: center;
color: var(--oki-encre);
text-decoration: none;
display: flex;
flex-direction: column;
align-items: center;
gap: 0.35rem;
padding: 1rem 0.8rem;
}
.carte-mode .emoji {
font-size: 1.6rem;
}
.carte-mode .nom {
font-weight: 750;
color: var(--oki-vert);
}
.carte-mode .desc {
font-size: 0.85rem;
color: var(--oki-encre-doux);
}
.carte-mode:hover {
border-color: var(--oki-vert-clair);
}
.carte-mode.choisi {
border-color: var(--oki-vert);
background: var(--oki-vert-doux);
}
.options {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.option-timer {
display: flex;
align-items: center;
gap: 0.6rem;
font-size: 1rem;
cursor: pointer;
}
.option-timer input {
width: 1.2rem;
height: 1.2rem;
accent-color: var(--oki-vert);
}
/* Bouton « Jouer » : fixe en zone du pouce sur mobile */
.zone-pouce {
position: fixed;
left: 0;
right: 0;
bottom: 0;
padding: 0.8rem 1rem calc(0.8rem + env(safe-area-inset-bottom));
background: linear-gradient(transparent, var(--oki-sable) 35%);
display: flex;
justify-content: center;
z-index: 10;
}
.jouer {
width: min(420px, 100%);
padding: 1rem;
font-size: 1.2rem;
}
@media (min-width: 768px) {
.hero h1 {
font-size: 3.6rem;
}
}
</style>
+25
View File
@@ -0,0 +1,25 @@
import { json } from '@sveltejs/kit';
import { getLieuPhotoById, sanitizeRound } from '$lib/server/lieux';
import { idsPourSeed, seedValide } from '$lib/server/tirage';
import type { RequestHandler } from './$types';
/**
* GET /api/defi/[seed] → { rounds: [5 rounds SANITISÉS] }.
* Même seed → mêmes lieux, même ordre, pour tous les joueurs (ADR-001 v1).
* Même format que /api/round : jamais de coordonnées, commune, région ni wikidata_id ;
* les photos passent par le proxy opaque /api/photo/<uuid>.
*/
export const GET: RequestHandler = ({ params }) => {
if (!seedValide(params.seed)) {
return json(
{ erreur: 'Seed invalide (440 caractères : lettres, chiffres, tiret, underscore)' },
{ status: 400 }
);
}
const rounds = idsPourSeed(params.seed).map((id) => {
const lieu = getLieuPhotoById(id);
if (!lieu) throw new Error(`Tirage incohérent : id inconnu (${id})`);
return sanitizeRound(lieu);
});
return json({ rounds }, { headers: { 'Cache-Control': 'no-store' } });
};
+51
View File
@@ -0,0 +1,51 @@
import { json } from '@sveltejs/kit';
import { getLieuById, scoreGuess, skipResult } from '$lib/server/lieux';
import type { RequestHandler } from './$types';
interface GuessBody {
id?: unknown;
lat?: unknown;
lon?: unknown;
hintsUsed?: unknown;
timeMs?: unknown;
skip?: unknown;
}
/**
* POST /api/guess { id, lat, lon, hintsUsed, timeMs? }
* → score recalculé serveur + vérité du lieu (révélée seulement ici).
* `skip: true` révèle la réponse avec un score de 0 (bouton « Passer »).
*/
export const POST: RequestHandler = async ({ request }) => {
let body: GuessBody;
try {
body = (await request.json()) as GuessBody;
} catch {
return json({ erreur: 'Corps JSON invalide' }, { status: 400 });
}
if (typeof body.id !== 'string') {
return json({ erreur: 'id manquant' }, { status: 400 });
}
const lieu = getLieuById(body.id);
if (!lieu) {
return json({ erreur: 'Lieu inconnu' }, { status: 404 });
}
if (body.skip === true) {
return json(skipResult(lieu));
}
const lat = Number(body.lat);
const lon = Number(body.lon);
if (!Number.isFinite(lat) || !Number.isFinite(lon) || Math.abs(lat) > 90 || Math.abs(lon) > 180) {
return json({ erreur: 'Coordonnées invalides' }, { status: 400 });
}
const hintsUsed = Math.max(0, Math.floor(Number(body.hintsUsed) || 0));
const timeMs =
typeof body.timeMs === 'number' && Number.isFinite(body.timeMs) && body.timeMs >= 0
? body.timeMs
: undefined;
return json(scoreGuess(lieu, { lat, lon }, hintsUsed, timeMs));
};
+10
View File
@@ -0,0 +1,10 @@
import { json } from '@sveltejs/kit';
import { catalogueExplorer } from '$lib/server/lieux';
import type { RequestHandler } from './$types';
/** GET /api/lieux → catalogue Explorer (coords arrondies à 0.05°, mode sans score). */
export const GET: RequestHandler = () => {
return json(catalogueExplorer(), {
headers: { 'Cache-Control': 'public, max-age=300' }
});
};
+88
View File
@@ -0,0 +1,88 @@
import sharp from 'sharp';
import { getLieuPhotoById, PHOTO_LARGEURS } from '$lib/server/lieux';
import type { RequestHandler } from './$types';
const USER_AGENT = 'JWE-OKI/2.0 (https://labola.o-k-i.net/ORGANISATION-KA-INTERNATIONALE/JWE; contact OKI)';
const TTL_MS = 24 * 60 * 60 * 1000; // 24 h
type Largeur = (typeof PHOTO_LARGEURS)[number];
const LARGEUR_DEFAUT: Largeur = 1200;
/** Cache mémoire : clé `${id}:${w}`, TTL 24 h. */
const cache = new Map<string, { expires: number; data: Buffer }>();
/** Déduplication des fetches en vol (même photo demandée en rafale). */
const enVol = new Map<string, Promise<Buffer | null>>();
/**
* Récupère la photo via l'URL Commons stockée dans le corpus (jamais d'URL
* fournie par le client — pas de proxy ouvert), puis la retraite avec sharp :
* - rotate() : applique l'orientation EXIF avant suppression des métadonnées ;
* - métadonnées : sharp ne conserve AUCUNE métadonnée (EXIF/GPS compris) sauf
* appel explicite à withMetadata() — le WebP produit est donc propre ;
* - conversion WebP + redimensionnement à la largeur demandée.
*/
async function chargerPhoto(id: string, w: Largeur): Promise<Buffer | null> {
const lieu = getLieuPhotoById(id);
if (!lieu) return null;
const res = await fetch(lieu.photo.url, { headers: { 'User-Agent': USER_AGENT } });
if (!res.ok) throw new Error(`commons ${res.status}`);
const brut = Buffer.from(await res.arrayBuffer());
return sharp(brut)
.rotate()
.resize({ width: w, withoutEnlargement: true })
.webp({ quality: 82 })
.toBuffer();
}
/**
* GET /api/photo/[id]?w=400|800|1200 → image/webp.
* `id` = uuid du lieu (déjà exposé par /api/round). 404 si lieu inconnu.
* L'URL ainsi produite est opaque : elle ne révèle ni le nom du fichier
* Commons ni le lieu (audit C4).
*/
export const GET: RequestHandler = async ({ params, url }) => {
const id = params.id;
const wParam = url.searchParams.get('w');
let w: Largeur = LARGEUR_DEFAUT;
if (wParam !== null) {
const n = Number(wParam);
if (!(PHOTO_LARGEURS as readonly number[]).includes(n)) {
return new Response('Largeur invalide (400, 800 ou 1200)', { status: 400 });
}
w = n as Largeur;
}
const cle = `${id}:${w}`;
const hit = cache.get(cle);
if (hit && hit.expires > Date.now()) {
return reponseWebp(hit.data);
}
// 404 immédiat si l'id est inconnu (avant tout fetch amont).
if (!getLieuPhotoById(id)) {
return new Response('Lieu inconnu', { status: 404 });
}
try {
let promesse = enVol.get(cle);
if (!promesse) {
promesse = chargerPhoto(id, w).finally(() => enVol.delete(cle));
enVol.set(cle, promesse);
}
const data = await promesse;
if (!data) return new Response('Lieu inconnu', { status: 404 });
cache.set(cle, { expires: Date.now() + TTL_MS, data });
return reponseWebp(data);
} catch {
return new Response('Photo indisponible', { status: 502 });
}
};
function reponseWebp(data: Buffer): Response {
return new Response(new Uint8Array(data), {
headers: {
'Content-Type': 'image/webp',
'Cache-Control': 'public, max-age=86400, immutable'
}
});
}
+34
View File
@@ -0,0 +1,34 @@
import { json } from '@sveltejs/kit';
import { getRandomLieu, getRandomStreet, sanitizeRound, sanitizeRoundStreet } from '$lib/server/lieux';
import type { RequestHandler } from './$types';
/**
* GET /api/round?region=&categorie=&exclude=id1,id2 → lieu aléatoire SANITISÉ.
* Avec `mode=street` : pioche dans le corpus Mapillary (catégorie ignorée,
* réponse avec `mapillaryId` au lieu de `photo`).
*/
export const GET: RequestHandler = ({ url }) => {
if (url.searchParams.get('mode') === 'street') {
const lieu = getRandomStreet({
region: url.searchParams.get('region'),
exclude: url.searchParams.get('exclude')
});
if (!lieu) {
return json({ erreur: 'Aucun lieu street disponible pour ces critères' }, { status: 404 });
}
return json(sanitizeRoundStreet(lieu), {
headers: { 'Cache-Control': 'no-store' }
});
}
const lieu = getRandomLieu({
region: url.searchParams.get('region'),
categorie: url.searchParams.get('categorie'),
exclude: url.searchParams.get('exclude')
});
if (!lieu) {
return json({ erreur: 'Aucun lieu disponible pour ces critères' }, { status: 404 });
}
return json(sanitizeRound(lieu), {
headers: { 'Cache-Control': 'no-store' }
});
};
+93
View File
@@ -0,0 +1,93 @@
import { json } from '@sveltejs/kit';
import type { WikiSummary } from '$lib/types';
import type { RequestHandler } from './$types';
const USER_AGENT = 'JWE-OKI/2.0 (https://labola.o-k-i.net/ORGANISATION-KA-INTERNATIONALE/JWE; contact OKI)';
const TTL_MS = 24 * 60 * 60 * 1000; // 24 h
const CACHE_CONTROL = 'public, max-age=86400';
const cache = new Map<string, { expires: number; summary: WikiSummary }>();
interface WbEntity {
labels?: { fr?: { value: string } };
sitelinks?: { frwiki?: { title: string } };
}
interface WbResponse {
entities?: Record<string, WbEntity>;
}
interface RestSummary {
title?: string;
extract?: string;
content_urls?: { desktop?: { page?: string } };
thumbnail?: { source?: string };
}
/** GET /api/wiki/[qid] → extrait Wikipédia FR normalisé (404 {reason:'no-frwiki'} si pas de sitelink fr). */
export const GET: RequestHandler = async ({ params, fetch }) => {
const qid = params.qid;
if (!/^Q\d+$/.test(qid)) {
return json({ erreur: 'Identifiant Wikidata invalide' }, { status: 400 });
}
const cached = cache.get(qid);
if (cached && cached.expires > Date.now()) {
return json(cached.summary, { headers: { 'Cache-Control': CACHE_CONTROL } });
}
const headers = { 'User-Agent': USER_AGENT, Accept: 'application/json' };
// 1. Wikidata : sitelink frwiki (+ libellé fr en fallback)
// Fallback de langue : fr UNIQUEMENT, volontairement sans repli sur en —
// l'absence d'article français devient un appel à contribution (Cas B), pas
// une redirection silencieuse vers Wikipédia en anglais.
const wbUrl = `https://www.wikidata.org/w/api.php?action=wbgetentities&ids=${encodeURIComponent(qid)}&props=sitelinks%7Clabels&sitefilter=frwiki&languages=fr&format=json`;
let entity: WbEntity | undefined;
try {
const res = await fetch(wbUrl, { headers });
if (!res.ok) throw new Error(`wikidata ${res.status}`);
// L'API résout les redirections : l'entité peut être indexée par le QID cible.
const entities = ((await res.json()) as WbResponse).entities ?? {};
entity = entities[qid] ?? Object.values(entities)[0];
} catch {
return json({ erreur: 'Wikidata injoignable' }, { status: 502 });
}
const titre = entity?.sitelinks?.frwiki?.title;
if (!titre) {
// QID existant mais pas d'article frwiki (cas intermédiaire, audit A3) :
// `reason: no-frwiki` permet au front d'afficher la variante « Pwen blindé —
// Pa nyen an fransé » (fiche Wikidata présente, article FR à traduire/créer),
// distincte du Cas B « lacune totale » (wikidata_id null côté lieu).
return json(
{ reason: 'no-frwiki' },
{ status: 404, headers: { 'Cache-Control': CACHE_CONTROL } }
);
}
// 2. Wikipédia FR : résumé de l'article
let data: RestSummary;
try {
const res = await fetch(
`https://fr.wikipedia.org/api/rest_v1/page/summary/${encodeURIComponent(titre)}`,
{ headers }
);
if (res.status === 404) return json({ erreur: 'Article introuvable' }, { status: 404 });
if (!res.ok) throw new Error(`wikipedia ${res.status}`);
data = (await res.json()) as RestSummary;
} catch {
return json({ erreur: 'Wikipédia injoignable' }, { status: 502 });
}
const summary: WikiSummary = {
qid,
title: data.title ?? titre,
extract: data.extract ?? '',
url: data.content_urls?.desktop?.page ?? `https://fr.wikipedia.org/wiki/${encodeURIComponent(titre)}`,
thumbnail: data.thumbnail?.source ?? null
};
cache.set(qid, { expires: Date.now() + TTL_MS, summary });
return json(summary, { headers: { 'Cache-Control': CACHE_CONTROL } });
};
+590
View File
@@ -0,0 +1,590 @@
<script lang="ts">
import { page } from '$app/state';
import GameMap from '$lib/components/GameMap.svelte';
import CarteRegions, { type MarqueurCarte } from '$lib/components/CarteRegions.svelte';
import PhotoPanel from '$lib/components/PhotoPanel.svelte';
import ResultPanel from '$lib/components/ResultPanel.svelte';
import TimerRing from '$lib/components/TimerRing.svelte';
import { t } from '$lib/i18n/store.svelte';
import { defi } from '$lib/stores/defi.svelte';
import type { Coordonnees, GuessResult, RoundPlace } from '$lib/types';
let { data } = $props();
const seed = $derived(data.seed);
const rounds = $derived(data.rounds);
const timerActif = $derived(page.url.searchParams.get('timer') === '1');
let place = $state<RoundPlace | null>(null);
let guess = $state<Coordonnees | null>(null);
let result = $state<GuessResult | null>(null);
let indicesMontres = $state<string[]>([]);
let erreur = $state(false);
let enCours = $state(false); // requête guess en vol
let timerRef: ReturnType<typeof TimerRing> | undefined = $state();
let bilan = $state(false); // écran final du défi
let lienCopie = $state(false); // retour visuel du bouton « Copier le lien »
const mancheCourante = $derived(defi.manches.length + 1);
const defiTermine = $derived(defi.termine);
// Marqueurs du récap SVG : position réelle (vert) + guess du joueur (corail),
// numérotés par manche ; une manche passée (guess null) n'a que le point réel.
const marqueursRecap = $derived(
defi.manches.flatMap((m, i): MarqueurCarte[] => {
const reel: MarqueurCarte = {
lat: m.result.coordonnees.lat,
lon: m.result.coordonnees.lon,
type: 'reel',
label: m.result.nom,
paire: i + 1
};
if (!m.guess) return [reel];
return [
reel,
{ lat: m.guess.lat, lon: m.guess.lon, type: 'guess', label: m.result.nom, paire: i + 1 }
];
})
);
// Les 5 lieux sont préchargés par le load : la manche courante suit l'état du store.
function chargerRound(): void {
guess = null;
result = null;
indicesMontres = [];
place = rounds[defi.manches.length] ?? null;
erreur = !place;
}
async function soumettre(skip: boolean): Promise<void> {
if (!place || result || enCours) return;
if (!skip && !guess) return;
enCours = true;
try {
const body: Record<string, unknown> = { id: place.id };
if (skip) {
body.skip = true;
} else {
body.lat = guess!.lat;
body.lon = guess!.lon;
body.hintsUsed = indicesMontres.length;
if (timerActif && timerRef) body.timeMs = timerRef.tempsMs();
}
const res = await fetch('/api/guess', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) throw new Error(String(res.status));
result = (await res.json()) as GuessResult;
defi.ajouter({ place, guess: skip ? null : guess, result });
} catch {
erreur = true;
} finally {
enCours = false;
}
}
function montrerIndice(): void {
if (!place) return;
const prochain = place.indices.find((i) => !indicesMontres.includes(i.texte));
if (prochain) indicesMontres = [...indicesMontres, prochain.texte];
}
function suivant(): void {
chargerRound();
}
function montrerBilan(): void {
bilan = true;
}
function rejouerDefi(): void {
defi.reinitialiser();
bilan = false;
lienCopie = false;
chargerRound();
}
/** Copie l'URL du défi dans le presse-papiers (repli : champ temporaire + sélection). */
async function copierLien(): Promise<void> {
const url = `${window.location.origin}/defi/${seed}`;
try {
await navigator.clipboard.writeText(url);
} catch {
// Contexte non sécurisé (HTTP) ou navigateur sans Clipboard API.
const champ = document.createElement('textarea');
champ.value = url;
document.body.appendChild(champ);
champ.select();
document.execCommand('copy');
champ.remove();
}
lienCopie = true;
setTimeout(() => (lienCopie = false), 2500);
}
/** Génère une image canvas téléchargeable : score total + lieux déjà révélés (V3). */
function partager(): void {
const canvas = document.createElement('canvas');
canvas.width = 1080;
canvas.height = 1080;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Fond sable + bandeau vert profond
ctx.fillStyle = '#f5efe2';
ctx.fillRect(0, 0, 1080, 1080);
ctx.fillStyle = '#0b3d2e';
ctx.fillRect(0, 0, 1080, 240);
ctx.fillStyle = '#fffdf8';
ctx.textAlign = 'center';
ctx.font = '800 96px system-ui, sans-serif';
ctx.fillText('JWE', 540, 130);
ctx.font = '600 44px system-ui, sans-serif';
ctx.fillText(t().modes.defi, 540, 200);
// Score total
ctx.fillStyle = '#0b3d2e';
ctx.font = '800 150px system-ui, sans-serif';
ctx.fillText(`${defi.total}`, 540, 420);
ctx.fillStyle = '#5a6b62';
ctx.font = '500 40px system-ui, sans-serif';
ctx.fillText(t().defi.scoreTotal, 540, 480);
// Manches : lieu, région, score
let y = 580;
for (const [i, m] of defi.manches.entries()) {
ctx.fillStyle = i % 2 === 0 ? '#e3efe7' : '#f5efe2';
ctx.fillRect(90, y - 44, 900, 74);
ctx.fillStyle = '#22302a';
ctx.textAlign = 'left';
ctx.font = '600 34px system-ui, sans-serif';
ctx.fillText(`${i + 1}. ${m.result.nom}`, 120, y);
ctx.fillStyle = '#17624a';
ctx.font = '500 30px system-ui, sans-serif';
ctx.fillText(t().regions[m.result.region], 120, y + 34);
ctx.textAlign = 'right';
ctx.fillStyle = '#0b3d2e';
ctx.font = '800 40px system-ui, sans-serif';
ctx.fillText(`${m.result.score}`, 960, y + 8);
y += 92;
}
ctx.fillStyle = '#5a6b62';
ctx.textAlign = 'center';
ctx.font = '500 30px system-ui, sans-serif';
ctx.fillText('labola.o-k-i.net', 540, 1010);
const a = document.createElement('a');
a.href = canvas.toDataURL('image/png');
a.download = 'jwe-defi.png';
a.click();
}
// (Ré)initialise le défi au montage et à chaque changement de seed :
// en navigation client d'un /defi/<seed> vers un autre, le composant est conservé.
let seedJouee = '';
$effect(() => {
if (seed === seedJouee) return;
seedJouee = seed;
defi.reinitialiser();
bilan = false;
lienCopie = false;
chargerRound();
});
</script>
<svelte:head>
<title>{t().app.titre}{t().modes.defi} — seed {seed}</title>
</svelte:head>
<div class="jeu">
{#if bilan}
<div class="bilan">
<h1>{t().defi.bilan}</h1>
<p class="seed-discret">{t().defi.titreSeed} <strong>{seed}</strong></p>
<p class="total">
<span class="valeur">{defi.total}</span>
<span class="unite">{t().defi.scoreTotal}</span>
</p>
<div class="bilan-carte">
<CarteRegions selectionnable={false} marqueurs={marqueursRecap} />
</div>
<ol class="recap">
{#each defi.manches as m, i (m.place.id)}
<li>
<span class="r-nom">{i + 1}. {m.result.nom}</span>
<span class="r-region">{t().regions[m.result.region]}</span>
<span class="r-score">{m.result.score} {t().resultat.points}</span>
</li>
{/each}
</ol>
<div class="bilan-actions">
<button type="button" class="btn btn-primaire" onclick={partager}>
{t().defi.partager}
</button>
<button type="button" class="btn btn-secondaire" onclick={() => void copierLien()}>
{lienCopie ? t().defi.lienCopie : t().defi.copierLien}
</button>
<button type="button" class="btn btn-secondaire" onclick={rejouerDefi}>
{t().resultat.rejouer}
</button>
<a href="/" class="btn btn-tertiaire">{t().resultat.retourAccueil}</a>
</div>
<p class="legende">
<span class="puce joueur" aria-hidden="true"></span> {t().defi.taPosition}
<span class="puce reelle" aria-hidden="true"></span> {t().defi.positionReelle}
</p>
</div>
{:else if erreur}
<div class="etat">
<p>{t().jeu.erreur}</p>
<button type="button" class="btn btn-secondaire" onclick={chargerRound}>
{t().jeu.reessayer}
</button>
</div>
{:else if place}
<div class="split" class:resultat={!!result}>
<section class="panneau-photo">
{#if result}
<div class="resultat-scroll">
<ResultPanel
{result}
creditPhoto={place.photo?.credit}
labelBouton={defiTermine ? t().resultat.voirBilan : t().resultat.suivant}
onsuivant={defiTermine ? montrerBilan : suivant}
/>
</div>
{:else if place.photo}
<PhotoPanel photo={place.photo} />
{/if}
</section>
<section class="panneau-carte">
<GameMap
bind:guess
real={result ? result.coordonnees : null}
distanceKm={result ? result.distanceKm : null}
interactive={!result}
onvalidate={() => void soumettre(false)}
/>
{#if !defiTermine}
<span class="badge-manche">{t().jeu.round} {Math.min(mancheCourante, 5)} {t().jeu.sur} 5</span>
{/if}
<span class="badge-seed">{t().defi.titreSeed} {seed}</span>
{#if timerActif && !result}
<div class="badge-timer">
<TimerRing bind:this={timerRef} actif={!result} />
</div>
{/if}
</section>
</div>
{#if !result}
<div class="barre-actions">
<div class="actions-secondaires">
<button
type="button"
class="btn btn-tertiaire"
onclick={montrerIndice}
disabled={indicesMontres.length >= place.indices.length}
>
{t().jeu.indice}
<span class="penalite">{t().jeu.indicePenalite}</span>
</button>
<button type="button" class="btn btn-secondaire" onclick={() => void soumettre(true)}>
{t().jeu.passer}
</button>
</div>
<button
type="button"
class="btn btn-primaire valider"
disabled={!guess || enCours}
onclick={() => void soumettre(false)}
>
{t().jeu.valider}
</button>
</div>
{#if indicesMontres.length > 0}
<aside class="indices" aria-live="polite">
{#each indicesMontres as texte, i (texte)}
<p class="indice"><strong>{t().jeu.indice} {i + 1}</strong>{texte}</p>
{/each}
</aside>
{/if}
{#if !guess}
<p class="aide-carte">{t().jeu.poserMarqueur}</p>
{/if}
{/if}
{:else}
<div class="etat"><p>{t().jeu.charger}</p></div>
{/if}
</div>
<style>
.jeu {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.etat {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
color: var(--oki-encre-doux);
}
.split {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.6rem;
padding: 0.6rem;
min-height: 0;
}
/* Mobile : photo 60 % haut, carte 40 % bas */
.panneau-photo {
flex: 0 0 58%;
min-height: 0;
}
.split.resultat .panneau-photo {
flex: 1 1 55%;
overflow-y: auto;
}
.panneau-carte {
position: relative;
flex: 1;
min-height: 220px;
}
.resultat-scroll {
height: 100%;
overflow-y: auto;
background: var(--oki-blanc);
border-radius: var(--oki-radius);
box-shadow: var(--oki-ombre);
padding: 1rem;
}
.badge-manche {
position: absolute;
top: 0.6rem;
right: 0.6rem;
background: rgba(255, 253, 248, 0.94);
color: var(--oki-vert);
border-radius: 999px;
padding: 0.25rem 0.8rem;
font-size: 0.82rem;
font-weight: 700;
box-shadow: var(--oki-ombre);
}
/* Seed visible mais discrète : les joueurs vérifient qu'ils jouent le même défi */
.badge-seed {
position: absolute;
top: 2.7rem;
right: 0.6rem;
background: rgba(255, 253, 248, 0.8);
color: var(--oki-encre-doux);
border-radius: 999px;
padding: 0.15rem 0.7rem;
font-size: 0.72rem;
font-weight: 600;
box-shadow: var(--oki-ombre);
}
.badge-timer {
position: absolute;
top: 0.6rem;
left: 3.4rem; /* à droite des boutons zoom */
}
/* Barre d'actions : fixe en zone du pouce (tiers inférieur) */
.barre-actions {
position: sticky;
bottom: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
padding: 0.7rem 0.8rem calc(0.7rem + env(safe-area-inset-bottom));
background: var(--oki-blanc);
border-top: 1px solid var(--oki-sable-fonce);
}
.actions-secondaires {
display: flex;
gap: 0.5rem;
}
.actions-secondaires .btn {
padding: 0.7rem 1rem;
font-size: 0.92rem;
}
.penalite {
font-size: 0.75rem;
font-weight: 500;
opacity: 0.8;
}
.valider {
flex: 0 0 auto;
padding: 0.9rem 1.4rem;
}
.indices {
padding: 0 1rem 0.5rem;
}
.indice {
margin: 0.25rem 0;
background: var(--oki-bleu-doux);
border-left: 4px solid var(--oki-bleu);
border-radius: var(--oki-radius-petit);
padding: 0.5rem 0.8rem;
font-size: 0.95rem;
}
.aide-carte {
margin: 0;
padding: 0 1rem 0.6rem;
text-align: center;
font-size: 0.88rem;
color: var(--oki-encre-doux);
}
/* Desktop : 50/50 */
@media (min-width: 768px) {
.split {
flex-direction: row;
}
.panneau-photo,
.split.resultat .panneau-photo {
flex: 1 1 50%;
}
.panneau-carte {
flex: 1 1 50%;
}
.barre-actions {
justify-content: center;
gap: 1.5rem;
}
}
/* — Écran bilan du défi — */
.bilan {
flex: 1;
width: 100%;
max-width: 860px;
margin: 0 auto;
padding: 1.2rem 1rem 2rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
.bilan h1 {
margin: 0;
text-align: center;
color: var(--oki-vert);
}
.seed-discret {
margin: 0;
text-align: center;
font-size: 0.9rem;
color: var(--oki-encre-doux);
}
.total {
margin: 0;
text-align: center;
}
.total .valeur {
font-size: 2.8rem;
font-weight: 800;
color: var(--oki-vert);
}
.total .unite {
margin-left: 0.4rem;
color: var(--oki-encre-doux);
}
.bilan-carte {
width: 100%;
max-width: 520px;
margin: 0 auto;
}
.recap {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.recap li {
display: flex;
align-items: baseline;
gap: 0.6rem;
background: var(--oki-blanc);
border-radius: var(--oki-radius-petit);
box-shadow: var(--oki-ombre);
padding: 0.55rem 0.9rem;
}
.r-nom {
font-weight: 700;
color: var(--oki-vert);
}
.r-region {
flex: 1;
color: var(--oki-encre-doux);
font-size: 0.9rem;
}
.r-score {
font-weight: 800;
}
.bilan-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 0.7rem;
}
.legende {
margin: 0;
text-align: center;
font-size: 0.85rem;
color: var(--oki-encre-doux);
}
.puce.joueur {
color: var(--oki-corail);
}
.puce.reelle {
color: var(--oki-vert);
}
</style>
+12
View File
@@ -0,0 +1,12 @@
import { error } from '@sveltejs/kit';
import type { RoundPlace } from '$lib/types';
import type { PageLoad } from './$types';
/** Charge les 5 rounds du défi seedé via l'API (mêmes lieux pour tous les joueurs). */
export const load: PageLoad = async ({ params, fetch }) => {
const res = await fetch(`/api/defi/${params.seed}`);
if (res.status === 400) error(400, 'Seed de défi invalide');
if (!res.ok) error(500, 'Impossible de charger ce défi');
const data = (await res.json()) as { rounds: RoundPlace[] };
return { seed: params.seed, rounds: data.rounds };
};
+263
View File
@@ -0,0 +1,263 @@
<script lang="ts">
import { onMount } from 'svelte';
import GameMap from '$lib/components/GameMap.svelte';
import WikiFiche from '$lib/components/WikiFiche.svelte';
import { t } from '$lib/i18n/store.svelte';
import { REGIONS } from '$lib/map/regions';
import type { ExplorerLieu, Region } from '$lib/types';
type Filtre = Region | 'TOUTES';
let lieux = $state<ExplorerLieu[]>([]);
let filtre = $state<Filtre>('TOUTES');
let selection = $state<ExplorerLieu | null>(null);
let erreur = $state(false);
const lieuxFiltres = $derived(
filtre === 'TOUTES' ? lieux : lieux.filter((l) => l.region === filtre)
);
const markers = $derived(
lieuxFiltres.map((l) => ({
// Id éphémère côté client (indice dans le catalogue) : /api/lieux n'expose
// plus l'uuid du lieu, pour ne pas corréler un id de round avec sa commune (C4).
id: String(lieux.indexOf(l)),
lat: l.coordonnees.lat,
lon: l.coordonnees.lon,
label: `${l.nom}${l.commune}`
}))
);
function ouvrir(id: string): void {
selection = lieux[Number(id)] ?? null;
}
onMount(() => {
void (async () => {
try {
const res = await fetch('/api/lieux');
if (!res.ok) throw new Error(String(res.status));
lieux = (await res.json()) as ExplorerLieu[];
} catch {
erreur = true;
}
})();
});
</script>
<svelte:head>
<title>{t().app.titre}{t().explorer.titre}</title>
</svelte:head>
<div class="explorer">
<div class="filtres" role="group" aria-label={t().explorer.filtrer}>
<button
type="button"
class:actif={filtre === 'TOUTES'}
aria-pressed={filtre === 'TOUTES'}
onclick={() => (filtre = 'TOUTES')}
>
{t().regions.TOUTES}
</button>
{#each REGIONS as r (r)}
<button
type="button"
class:actif={filtre === r}
aria-pressed={filtre === r}
onclick={() => (filtre = r)}
>
{t().regions[r]}
</button>
{/each}
</div>
<div class="carte-explorer">
{#if erreur}
<p class="erreur">{t().jeu.erreur}</p>
{:else}
<GameMap interactive={false} {markers} onmarkerclick={ouvrir} />
{/if}
</div>
<!-- Panneau latéral (desktop) / bottom sheet (mobile) -->
<aside class="fiche" class:ouvert={!!selection} aria-live="polite">
{#if selection}
<button
type="button"
class="fermer"
aria-label={t().explorer.fermer}
onclick={() => (selection = null)}
>
</button>
<figure class="fiche-photo">
<img
src={selection.photo.url}
alt={selection.photo.alt}
loading="lazy"
decoding="async"
/>
<figcaption>{selection.photo.credit}</figcaption>
</figure>
<h1>{selection.nom}</h1>
{#if selection.nom_creole && selection.nom_creole !== selection.nom}
<p class="creole">{selection.nom_creole}</p>
{/if}
<p class="localisation">
{t().resultat.commune} : {selection.commune}{t().regions[selection.region]}
</p>
{#key selection.nom}
<WikiFiche nom={selection.nom} wikidataId={selection.wikidata_id} />
{/key}
{:else}
<p class="vide">{t().explorer.aucuneFiche}</p>
{/if}
</aside>
</div>
<style>
.explorer {
flex: 1;
display: flex;
flex-direction: column;
position: relative;
min-height: 0;
}
.filtres {
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
padding: 0.6rem 0.8rem;
background: var(--oki-blanc);
border-bottom: 1px solid var(--oki-sable-fonce);
}
.filtres button {
border: 1.5px solid var(--oki-vert-clair);
background: transparent;
color: var(--oki-vert);
border-radius: 999px;
padding: 0.35rem 0.9rem;
font-size: 0.88rem;
font-weight: 650;
cursor: pointer;
}
.filtres button.actif {
background: var(--oki-vert);
border-color: var(--oki-vert);
color: #fff;
}
.carte-explorer {
flex: 1;
min-height: 0;
padding: 0.6rem;
}
.erreur {
text-align: center;
color: var(--oki-encre-doux);
}
/* Bottom sheet mobile */
.fiche {
position: absolute;
left: 0;
right: 0;
bottom: 0;
max-height: 62%;
overflow-y: auto;
background: var(--oki-blanc);
border-radius: var(--oki-radius) var(--oki-radius) 0 0;
box-shadow: 0 -4px 18px rgba(11, 61, 46, 0.2);
padding: 1rem;
transform: translateY(calc(100% - 3.2rem));
transition: transform 0.25s ease;
}
.fiche.ouvert {
transform: translateY(0);
}
.fiche .vide {
margin: 0;
text-align: center;
color: var(--oki-encre-doux);
padding-bottom: 0.4rem;
}
.fermer {
position: absolute;
top: 0.6rem;
right: 0.6rem;
border: none;
background: var(--oki-vert-doux);
color: var(--oki-vert);
width: 2rem;
height: 2rem;
border-radius: 50%;
font-size: 1rem;
cursor: pointer;
}
.fiche-photo {
margin: 0 0 0.6rem;
}
.fiche-photo img {
width: 100%;
max-height: 200px;
object-fit: cover;
border-radius: var(--oki-radius-petit);
display: block;
}
.fiche-photo figcaption {
font-size: 0.72rem;
color: var(--oki-encre-doux);
margin-top: 0.2rem;
}
.fiche h1 {
margin: 0;
font-size: 1.3rem;
color: var(--oki-vert);
}
.creole {
margin: 0.1rem 0 0;
font-style: italic;
color: var(--oki-vert-clair);
}
.localisation {
margin: 0.3rem 0 0.8rem;
color: var(--oki-encre-doux);
font-size: 0.92rem;
}
/* Panneau latéral desktop */
@media (min-width: 768px) {
.fiche {
left: auto;
top: 0;
right: 0;
bottom: 0;
width: 380px;
max-height: none;
border-radius: var(--oki-radius) 0 0 var(--oki-radius);
transform: translateX(calc(100% - 3.2rem));
}
.fiche.ouvert {
transform: translateX(0);
}
}
@media (prefers-reduced-motion: reduce) {
.fiche {
transition: none;
}
}
</style>
+564
View File
@@ -0,0 +1,564 @@
<script lang="ts">
import { onMount } from 'svelte';
import { page } from '$app/state';
import GameMap from '$lib/components/GameMap.svelte';
import CarteRegions, { type MarqueurCarte } from '$lib/components/CarteRegions.svelte';
import PhotoPanel from '$lib/components/PhotoPanel.svelte';
import StreetPanel from '$lib/components/StreetPanel.svelte';
import ResultPanel from '$lib/components/ResultPanel.svelte';
import TimerRing from '$lib/components/TimerRing.svelte';
import { t } from '$lib/i18n/store.svelte';
import { defi } from '$lib/stores/defi.svelte';
import type { Coordonnees, GuessResult, RoundPlace } from '$lib/types';
let { data } = $props();
const mode = $derived(data.mode);
const regionParam = $derived(page.url.searchParams.get('region'));
const timerActif = $derived(page.url.searchParams.get('timer') === '1');
let place = $state<RoundPlace | null>(null);
let guess = $state<Coordonnees | null>(null);
let result = $state<GuessResult | null>(null);
let indicesMontres = $state<string[]>([]);
let chargement = $state(true);
let erreur = $state(false);
let enCours = $state(false); // requête guess en vol
let timerRef: ReturnType<typeof TimerRing> | undefined = $state();
let joues = $state<string[]>([]); // ids déjà joués (évite les répétitions)
let bilan = $state(false); // écran final du défi
const estDefi = $derived(mode === 'defi');
const mancheCourante = $derived(defi.manches.length + 1);
const defiTermine = $derived(estDefi && defi.termine);
// Marqueurs du récap SVG : position réelle (vert) + guess du joueur (corail),
// numérotés par manche ; une manche passée (guess null) n'a que le point réel.
const marqueursRecap = $derived(
defi.manches.flatMap((m, i): MarqueurCarte[] => {
const reel: MarqueurCarte = {
lat: m.result.coordonnees.lat,
lon: m.result.coordonnees.lon,
type: 'reel',
label: m.result.nom,
paire: i + 1
};
if (!m.guess) return [reel];
return [
reel,
{ lat: m.guess.lat, lon: m.guess.lon, type: 'guess', label: m.result.nom, paire: i + 1 }
];
})
);
async function chargerRound(): Promise<void> {
chargement = true;
erreur = false;
place = null;
guess = null;
result = null;
indicesMontres = [];
try {
const params = new URLSearchParams();
if (regionParam) params.set('region', regionParam);
if (mode === 'monument') params.set('categorie', 'MONUMENT');
if (mode === 'lieu') params.set('categorie', 'LIEU');
if (mode === 'street') params.set('mode', 'street');
if (joues.length > 0) params.set('exclude', joues.join(','));
const res = await fetch(`/api/round?${params}`);
if (!res.ok) throw new Error(String(res.status));
place = (await res.json()) as RoundPlace;
} catch {
erreur = true;
} finally {
chargement = false;
}
}
async function soumettre(skip: boolean): Promise<void> {
if (!place || result || enCours) return;
if (!skip && !guess) return;
enCours = true;
try {
const body: Record<string, unknown> = { id: place.id };
if (skip) {
body.skip = true;
} else {
body.lat = guess!.lat;
body.lon = guess!.lon;
body.hintsUsed = indicesMontres.length;
if (timerActif && timerRef) body.timeMs = timerRef.tempsMs();
}
const res = await fetch('/api/guess', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
});
if (!res.ok) throw new Error(String(res.status));
result = (await res.json()) as GuessResult;
joues = [...joues, place.id];
if (estDefi) {
defi.ajouter({ place, guess: skip ? null : guess, result });
}
} catch {
erreur = true;
} finally {
enCours = false;
}
}
function montrerIndice(): void {
if (!place) return;
const prochain = place.indices.find((i) => !indicesMontres.includes(i.texte));
if (prochain) indicesMontres = [...indicesMontres, prochain.texte];
}
function suivant(): void {
void chargerRound();
}
function montrerBilan(): void {
bilan = true;
}
function rejouerDefi(): void {
defi.reinitialiser();
joues = [];
bilan = false;
void chargerRound();
}
/** Génère une image canvas téléchargeable : score total + régions jouées. */
function partager(): void {
const canvas = document.createElement('canvas');
canvas.width = 1080;
canvas.height = 1080;
const ctx = canvas.getContext('2d');
if (!ctx) return;
// Fond sable + bandeau vert profond
ctx.fillStyle = '#f5efe2';
ctx.fillRect(0, 0, 1080, 1080);
ctx.fillStyle = '#0b3d2e';
ctx.fillRect(0, 0, 1080, 240);
ctx.fillStyle = '#fffdf8';
ctx.textAlign = 'center';
ctx.font = '800 96px system-ui, sans-serif';
ctx.fillText('JWE', 540, 130);
ctx.font = '600 44px system-ui, sans-serif';
ctx.fillText(t().modes.defi, 540, 200);
// Score total
ctx.fillStyle = '#0b3d2e';
ctx.font = '800 150px system-ui, sans-serif';
ctx.fillText(`${defi.total}`, 540, 420);
ctx.fillStyle = '#5a6b62';
ctx.font = '500 40px system-ui, sans-serif';
ctx.fillText(t().defi.scoreTotal, 540, 480);
// Manches : lieu, région, score
let y = 580;
for (const [i, m] of defi.manches.entries()) {
ctx.fillStyle = i % 2 === 0 ? '#e3efe7' : '#f5efe2';
ctx.fillRect(90, y - 44, 900, 74);
ctx.fillStyle = '#22302a';
ctx.textAlign = 'left';
ctx.font = '600 34px system-ui, sans-serif';
ctx.fillText(`${i + 1}. ${m.result.nom}`, 120, y);
ctx.fillStyle = '#17624a';
ctx.font = '500 30px system-ui, sans-serif';
ctx.fillText(t().regions[m.result.region], 120, y + 34);
ctx.textAlign = 'right';
ctx.fillStyle = '#0b3d2e';
ctx.font = '800 40px system-ui, sans-serif';
ctx.fillText(`${m.result.score}`, 960, y + 8);
y += 92;
}
ctx.fillStyle = '#5a6b62';
ctx.textAlign = 'center';
ctx.font = '500 30px system-ui, sans-serif';
ctx.fillText('labola.o-k-i.net', 540, 1010);
const a = document.createElement('a');
a.href = canvas.toDataURL('image/png');
a.download = 'jwe-defi.png';
a.click();
}
onMount(() => {
// Nouveau défi : on repart de zéro quand on arrive sur la première manche.
if (estDefi && defi.termine) defi.reinitialiser();
void chargerRound();
});
</script>
<svelte:head>
<title>{t().app.titre}{t().modes[mode]}</title>
</svelte:head>
<div class="jeu">
{#if bilan}
<div class="bilan">
<h1>{t().defi.bilan}</h1>
<p class="total">
<span class="valeur">{defi.total}</span>
<span class="unite">{t().defi.scoreTotal}</span>
</p>
<div class="bilan-carte">
<CarteRegions selectionnable={false} marqueurs={marqueursRecap} />
</div>
<ol class="recap">
{#each defi.manches as m, i (m.place.id)}
<li>
<span class="r-nom">{i + 1}. {m.result.nom}</span>
<span class="r-region">{t().regions[m.result.region]}</span>
<span class="r-score">{m.result.score} {t().resultat.points}</span>
</li>
{/each}
</ol>
<div class="bilan-actions">
<button type="button" class="btn btn-primaire" onclick={partager}>
{t().defi.partager}
</button>
<button type="button" class="btn btn-secondaire" onclick={rejouerDefi}>
{t().resultat.rejouer}
</button>
<a href="/" class="btn btn-tertiaire">{t().resultat.retourAccueil}</a>
</div>
<p class="legende">
<span class="puce joueur" aria-hidden="true"></span> {t().defi.taPosition}
<span class="puce reelle" aria-hidden="true"></span> {t().defi.positionReelle}
</p>
</div>
{:else if chargement}
<div class="etat"><p>{t().jeu.charger}</p></div>
{:else if erreur}
<div class="etat">
<p>{t().jeu.erreur}</p>
<button type="button" class="btn btn-secondaire" onclick={() => void chargerRound()}>
{t().jeu.reessayer}
</button>
</div>
{:else if place}
<div class="split" class:resultat={!!result}>
<section class="panneau-photo">
{#if result}
<div class="resultat-scroll">
<ResultPanel
{result}
creditPhoto={place.photo?.credit ?? place.credit}
labelBouton={estDefi && defiTermine ? t().resultat.voirBilan : t().resultat.suivant}
onsuivant={estDefi && defiTermine ? montrerBilan : suivant}
/>
</div>
{:else if place.mapillaryId}
<StreetPanel mapillaryId={place.mapillaryId} credit={place.credit} />
{:else if place.photo}
<PhotoPanel photo={place.photo} />
{/if}
</section>
<section class="panneau-carte">
<GameMap
bind:guess
real={result ? result.coordonnees : null}
distanceKm={result ? result.distanceKm : null}
interactive={!result}
onvalidate={() => void soumettre(false)}
/>
{#if estDefi && !defiTermine}
<span class="badge-manche">{t().jeu.round} {Math.min(mancheCourante, 5)} {t().jeu.sur} 5</span>
{/if}
{#if timerActif && !result}
<div class="badge-timer">
<TimerRing bind:this={timerRef} actif={!result} />
</div>
{/if}
</section>
</div>
{#if !result}
<div class="barre-actions">
<div class="actions-secondaires">
<button
type="button"
class="btn btn-tertiaire"
onclick={montrerIndice}
disabled={indicesMontres.length >= place.indices.length}
>
{t().jeu.indice}
<span class="penalite">{t().jeu.indicePenalite}</span>
</button>
<button type="button" class="btn btn-secondaire" onclick={() => void soumettre(true)}>
{t().jeu.passer}
</button>
</div>
<button
type="button"
class="btn btn-primaire valider"
disabled={!guess || enCours}
onclick={() => void soumettre(false)}
>
{t().jeu.valider}
</button>
</div>
{#if indicesMontres.length > 0}
<aside class="indices" aria-live="polite">
{#each indicesMontres as texte, i (texte)}
<p class="indice"><strong>{t().jeu.indice} {i + 1}</strong>{texte}</p>
{/each}
</aside>
{/if}
{#if !guess}
<p class="aide-carte">{t().jeu.poserMarqueur}</p>
{/if}
{/if}
{/if}
</div>
<style>
.jeu {
flex: 1;
display: flex;
flex-direction: column;
min-height: 0;
}
.etat {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 1rem;
color: var(--oki-encre-doux);
}
.split {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.6rem;
padding: 0.6rem;
min-height: 0;
}
/* Mobile : photo 60 % haut, carte 40 % bas */
.panneau-photo {
flex: 0 0 58%;
min-height: 0;
}
.split.resultat .panneau-photo {
flex: 1 1 55%;
overflow-y: auto;
}
.panneau-carte {
position: relative;
flex: 1;
min-height: 220px;
}
.resultat-scroll {
height: 100%;
overflow-y: auto;
background: var(--oki-blanc);
border-radius: var(--oki-radius);
box-shadow: var(--oki-ombre);
padding: 1rem;
}
.badge-manche {
position: absolute;
top: 0.6rem;
right: 0.6rem;
background: rgba(255, 253, 248, 0.94);
color: var(--oki-vert);
border-radius: 999px;
padding: 0.25rem 0.8rem;
font-size: 0.82rem;
font-weight: 700;
box-shadow: var(--oki-ombre);
}
.badge-timer {
position: absolute;
top: 0.6rem;
left: 3.4rem; /* à droite des boutons zoom */
}
/* Barre d'actions : fixe en zone du pouce (tiers inférieur) */
.barre-actions {
position: sticky;
bottom: 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
padding: 0.7rem 0.8rem calc(0.7rem + env(safe-area-inset-bottom));
background: var(--oki-blanc);
border-top: 1px solid var(--oki-sable-fonce);
}
.actions-secondaires {
display: flex;
gap: 0.5rem;
}
.actions-secondaires .btn {
padding: 0.7rem 1rem;
font-size: 0.92rem;
}
.penalite {
font-size: 0.75rem;
font-weight: 500;
opacity: 0.8;
}
.valider {
flex: 0 0 auto;
padding: 0.9rem 1.4rem;
}
.indices {
padding: 0 1rem 0.5rem;
}
.indice {
margin: 0.25rem 0;
background: var(--oki-bleu-doux);
border-left: 4px solid var(--oki-bleu);
border-radius: var(--oki-radius-petit);
padding: 0.5rem 0.8rem;
font-size: 0.95rem;
}
.aide-carte {
margin: 0;
padding: 0 1rem 0.6rem;
text-align: center;
font-size: 0.88rem;
color: var(--oki-encre-doux);
}
/* Desktop : 50/50 */
@media (min-width: 768px) {
.split {
flex-direction: row;
}
.panneau-photo,
.split.resultat .panneau-photo {
flex: 1 1 50%;
}
.panneau-carte {
flex: 1 1 50%;
}
.barre-actions {
justify-content: center;
gap: 1.5rem;
}
}
/* — Écran bilan du défi — */
.bilan {
flex: 1;
width: 100%;
max-width: 860px;
margin: 0 auto;
padding: 1.2rem 1rem 2rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
.bilan h1 {
margin: 0;
text-align: center;
color: var(--oki-vert);
}
.total {
margin: 0;
text-align: center;
}
.total .valeur {
font-size: 2.8rem;
font-weight: 800;
color: var(--oki-vert);
}
.total .unite {
margin-left: 0.4rem;
color: var(--oki-encre-doux);
}
.bilan-carte {
width: 100%;
max-width: 520px;
margin: 0 auto;
}
.recap {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.recap li {
display: flex;
align-items: baseline;
gap: 0.6rem;
background: var(--oki-blanc);
border-radius: var(--oki-radius-petit);
box-shadow: var(--oki-ombre);
padding: 0.55rem 0.9rem;
}
.r-nom {
font-weight: 700;
color: var(--oki-vert);
}
.r-region {
flex: 1;
color: var(--oki-encre-doux);
font-size: 0.9rem;
}
.r-score {
font-weight: 800;
}
.bilan-actions {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 0.7rem;
}
.legende {
margin: 0;
text-align: center;
font-size: 0.85rem;
color: var(--oki-encre-doux);
}
.puce.joueur {
color: var(--oki-corail);
}
.puce.reelle {
color: var(--oki-vert);
}
</style>
+12
View File
@@ -0,0 +1,12 @@
import { error } from '@sveltejs/kit';
import type { GameMode } from '$lib/types';
import type { PageLoad } from './$types';
const MODES: GameMode[] = ['monument', 'lieu', 'defi', 'street'];
export const load: PageLoad = ({ params }) => {
if (!MODES.includes(params.mode as GameMode)) {
error(404, 'Mode inconnu');
}
return { mode: params.mode as GameMode };
};
+66
View File
@@ -0,0 +1,66 @@
/// <reference types="@sveltejs/kit" />
/// <reference no-default-lib="true"/>
/// <reference lib="esnext" />
/// <reference lib="webworker" />
import { build, files, version } from '$service-worker';
const sw = self as unknown as ServiceWorkerGlobalScope;
const APP_SHELL = `jwe-shell-${version}`; // immuable, recréé à chaque build
const PHOTOS = 'jwe-photos'; // stale-while-revalidate
const ASSETS = [...build, ...files];
sw.addEventListener('install', (event) => {
event.waitUntil(caches.open(APP_SHELL).then((cache) => cache.addAll(ASSETS)));
});
sw.addEventListener('activate', (event) => {
event.waitUntil(
caches.keys().then((keys) =>
Promise.all(
keys
.filter((key) => key !== APP_SHELL && key !== PHOTOS)
.map((key) => caches.delete(key))
)
)
);
});
function isPhoto(url: URL): boolean {
return (
url.hostname === 'upload.wikimedia.org' ||
(url.hostname === 'commons.wikimedia.org' && url.pathname.startsWith('/wiki/Special:FilePath')) ||
// Proxy photo maison (mode jeu) — réponses immutables, WebP sans métadonnées
(url.origin === sw.location.origin && url.pathname.startsWith('/api/photo/'))
);
}
sw.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
if (event.request.method !== 'GET') return;
// App shell : cache d'abord
if (ASSETS.includes(url.pathname)) {
event.respondWith(caches.match(event.request).then((r) => r ?? fetch(event.request)));
return;
}
// Photos Wikimedia : stale-while-revalidate
if (isPhoto(url)) {
event.respondWith(
caches.open(PHOTOS).then(async (cache) => {
const cached = await cache.match(event.request);
const frais = fetch(event.request)
.then((res) => {
if (res.ok) void cache.put(event.request, res.clone());
return res;
})
.catch(() => cached as Response);
return cached ?? frais;
})
);
return;
}
});

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 4.2 KiB

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" fill="#0b3d2e"/>
<circle cx="256" cy="256" r="130" fill="none" stroke="#f5efe2" stroke-width="22"/>
<path d="M256 148 L312 330 L256 292 L200 330 Z" fill="#e4572e"/>
</svg>

After

Width:  |  Height:  |  Size: 269 B

+5
View File
@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<rect width="512" height="512" rx="96" fill="#0b3d2e"/>
<circle cx="256" cy="256" r="150" fill="none" stroke="#f5efe2" stroke-width="26"/>
<path d="M256 130 L322 344 L256 300 L190 344 Z" fill="#e4572e"/>
</svg>

After

Width:  |  Height:  |  Size: 277 B

+25
View File
@@ -0,0 +1,25 @@
{
"name": "JWE — Jeu de géolocalisation OKI",
"short_name": "JWE",
"description": "Devine la commune à partir d'une photo — Guadeloupe, Martinique, Guyane, La Réunion.",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#f5efe2",
"theme_color": "#0b3d2e",
"lang": "fr",
"icons": [
{
"src": "/icon.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "/icon-maskable.svg",
"sizes": "any",
"type": "image/svg+xml",
"purpose": "maskable"
}
]
}
+12
View File
@@ -0,0 +1,12 @@
import adapter from '@sveltejs/adapter-node';
import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
/** @type {import('@sveltejs/kit').Config} */
const config = {
preprocess: vitePreprocess(),
kit: {
adapter: adapter()
}
};
export default config;
+14
View File
@@ -0,0 +1,14 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
}
+6
View File
@@ -0,0 +1,6 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [sveltekit()]
});
+87
View File
@@ -0,0 +1,87 @@
# Crédits photos — JWE
Les 41 photos du corpus `app/src/lib/server/data/lieux.json` proviennent de Wikimedia Commons.
Chaque fichier est sous licence libre (Creative Commons, CC0 ou domaine public) — vérifiée via l'API Commons
(`LicenseShortName`) et l'URL `Special:FilePath` testée en HTTP 200.
| # | Lieu | Région | Fichier Commons | Auteur | Licence | Page de description |
|---|------|--------|-----------------|--------|---------|---------------------|
| 1 | Fort Delgrès | GUADELOUPE | Entrée du Fort Delgrès.JPG | LPLT | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Entr%C3%A9e_du_Fort_Delgr%C3%A8s.JPG |
| 2 | Mémorial ACTe | GUADELOUPE | Photographie de haut du mémorial acte.jpg | Bjrmoicorla | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Photographie_de_haut_du_m%C3%A9morial_acte.jpg |
| 3 | Fort Napoléon des Saintes | GUADELOUPE | Fort Napoléon dans l'archipel des Saintes.jpg | Gauthier Geoffroy | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Fort_Napol%C3%A9on_dans_l'archipel_des_Saintes.jpg |
| 4 | Cathédrale Notre-Dame-de-Guadeloupe | GUADELOUPE | Cathédrale Notre-Dame-de-Guadeloupe - Sept. 2013 (1).JPG | Aristoi | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Cath%C3%A9drale_Notre-Dame-de-Guadeloupe_-_Sept._2013_(1).JPG |
| 5 | Habitation La Grivelière | GUADELOUPE | Habitation La Grivelière 2.JPG | LPLT | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Habitation_La_Griveli%C3%A8re_2.JPG |
| 6 | Soufrière | GUADELOUPE | Guadeloupe 114 - Sommet de la Soufrière 1467m - Guadeloupe.jpg | Ofol | CC-BY-2.5 | https://commons.wikimedia.org/wiki/File:Guadeloupe_114_-_Sommet_de_la_Soufri%C3%A8re_1467m_-_Guadeloupe.jpg |
| 7 | Pointe des Châteaux | GUADELOUPE | Pointedeschateaux.jpg | bobyfume | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Pointedeschateaux.jpg |
| 8 | Jardin botanique de Deshaies | GUADELOUPE | Jardin Botanique - étang aux nénuphars.JPG | Grook Da Oger | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Jardin_Botanique_-_%C3%A9tang_aux_n%C3%A9nuphars.JPG |
| 9 | Plage de Bois Jolan | GUADELOUPE | Plage de St Anne (bois jolan).jpg | Filo gèn' | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Plage_de_St_Anne_(bois_jolan).jpg |
| 10 | Marché de la Darse | GUADELOUPE | Marché de la Darse (épices).jpg | Filo gèn' | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:March%C3%A9_de_la_Darse_(%C3%A9pices).jpg |
| 11 | Fort Saint-Louis | MARTINIQUE | Fort Saint-Louis vu du Carénage 02.jpg | UHF | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Fort_Saint-Louis_vu_du_Car%C3%A9nage_02.jpg |
| 12 | Bibliothèque Schœlcher | MARTINIQUE | Fort-de-France - 2014 - Bibliothèque Schœlcher (1).jpg | Aristoi | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Fort-de-France_-_2014_-_Biblioth%C3%A8que_Sch%C5%93lcher_(1).jpg |
| 13 | Cathédrale Saint-Louis de Fort-de-France | MARTINIQUE | Cathédrale Saint Louis.jpg | Pierre PONCHEL | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Cath%C3%A9drale_Saint_Louis.jpg |
| 14 | Habitation Clément | MARTINIQUE | Habitation Clément 001.jpg | Tux-Man | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Habitation_Cl%C3%A9ment_001.jpg |
| 15 | Église du Sacré-Cœur de Balata | MARTINIQUE | Sacré-coeur-balata-FdF.JPG | Jean-Louis Lascoux | CC-BY-3.0 | https://commons.wikimedia.org/wiki/File:Sacr%C3%A9-coeur-balata-FdF.JPG |
| 16 | Montagne Pelée | MARTINIQUE | La Pelée vue du Carbet.jpg | Jurassi | Domaine public | https://commons.wikimedia.org/wiki/File:La_Pel%C3%A9e_vue_du_Carbet.jpg |
| 17 | Presqu'île de la Caravelle | MARTINIQUE | Anse non nommée à la pointe de la presqu'île de la Caravelle.jpg | Enrevseluj | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Anse_non_nomm%C3%A9e_%C3%A0_la_pointe_de_la_presqu'%C3%AEle_de_la_Caravelle.jpg |
| 18 | Anse-Dufour | MARTINIQUE | Anse Dufour (Les Anses-d'Arlet, Martinique) - 01.jpg | Thérèse Gaigé | CC0-1.0 | https://commons.wikimedia.org/wiki/File:Anse_Dufour_(Les_Anses-d'Arlet%2C_Martinique)_-_01.jpg |
| 19 | Anse Noire | MARTINIQUE | Anse Noire (Les Anses-d'Arlet, Martinique) - 01.jpg | Thérèse Gaigé | CC0-1.0 | https://commons.wikimedia.org/wiki/File:Anse_Noire_(Les_Anses-d'Arlet%2C_Martinique)_-_01.jpg |
| 20 | Savane des pétrifications | MARTINIQUE | Martinique savane des pétrifications 1.jpg | Esam335 | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Martinique_savane_des_p%C3%A9trifications_1.jpg |
| 21 | Centre spatial guyanais | GUYANE | Ariane 5ECA on its launch platform on its way to lauch pad ELA-3.jpg | elisabetta_monaco | CC-BY-2.0 | https://commons.wikimedia.org/wiki/File:Ariane_5ECA_on_its_launch_platform_on_its_way_to_lauch_pad_ELA-3.jpg |
| 22 | Îles du Salut | GUYANE | ILES et BAGNE 037.JPG | davric | Domaine public | https://commons.wikimedia.org/wiki/File:ILES_et_BAGNE_037.JPG |
| 23 | Cathédrale Saint-Sauveur de Cayenne | GUYANE | Cathédrale Saint-Sauveur de Cayenne.jpg | Don-vip | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Cath%C3%A9drale_Saint-Sauveur_de_Cayenne.jpg |
| 24 | Fort Cépérou | GUYANE | Cayenne Fort Cépérou 2013.jpg | Cayambe | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Cayenne_Fort_C%C3%A9p%C3%A9rou_2013.jpg |
| 25 | Camp de la Transportation (bagne) | GUYANE | Camp de la Transportation-13.jpg | Psu973 | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Camp_de_la_Transportation-13.jpg |
| 26 | Marais de Kaw-Roura | GUYANE | Marais de Kaw - Guyane 1.jpg | Jacques MARTIN 97311 | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Marais_de_Kaw_-_Guyane_1.jpg |
| 27 | Place des Palmistes | GUYANE | Cayenne Place des palmistes.jpg | Cayambe | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Cayenne_Place_des_palmistes.jpg |
| 28 | Crique Cacao | GUYANE | Crique Cacao.jpg | Aandrem | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Crique_Cacao.jpg |
| 29 | Plage de Montjoly | GUYANE | Plages de Rémire-Montjoly - Guyane.JPG | Lebrouillard | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Plages_de_R%C3%A9mire-Montjoly_-_Guyane.JPG |
| 30 | Îlet la Mère | GUYANE | Ilet la Mère débarcadère 2013.jpg | Cayambe | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:Ilet_la_M%C3%A8re_d%C3%A9barcad%C3%A8re_2013.jpg |
| 31 | Église Notre-Dame des Laves | REUNION | Église Notre-Dame-des-Laves @ Piton Sainte-Rose 05.jpg | Rémih | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:%C3%89glise_Notre-Dame-des-Laves_%40_Piton_Sainte-Rose_05.jpg |
| 32 | Cimetière marin de Saint-Paul | REUNION | Marine Cemetery of Saint-Paul (Réunion Island).jpg | dalbera | CC-BY-2.0 | https://commons.wikimedia.org/wiki/File:Marine_Cemetery_of_Saint-Paul_(R%C3%A9union_Island).jpg |
| 33 | Villa Folio | REUNION | Maison Folio.jpg | Nanère | CC-BY-2.5 | https://commons.wikimedia.org/wiki/File:Maison_Folio.jpg |
| 34 | Domaine du Grand Hazier | REUNION | GrandHazierEntree.jpg | David Rofas | CC-BY-3.0 | https://commons.wikimedia.org/wiki/File:GrandHazierEntree.jpg |
| 35 | Temple du Colosse | REUNION | Temple-du-Colosse.JPG | Thierry Caro | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Temple-du-Colosse.JPG |
| 36 | Piton de la Fournaise | REUNION | Piton de La Fournaise - Paysage de l'île de La Réunion.jpg | Alexandre Péribé | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Piton_de_La_Fournaise_-_Paysage_de_l'%C3%AEle_de_La_R%C3%A9union.jpg |
| 37 | Piton des Neiges | REUNION | Piton des Neiges1.JPG | Dunog | Domaine public | https://commons.wikimedia.org/wiki/File:Piton_des_Neiges1.JPG |
| 38 | Cirque de Mafate | REUNION | 14-07-2011 Grand Bénare (26) Mafate (version améliorée).jpg | Mamphi | CC-BY-SA-3.0 | https://commons.wikimedia.org/wiki/File:14-07-2011_Grand_B%C3%A9nare_(26)_Mafate_(version_am%C3%A9lior%C3%A9e).jpg |
| 39 | Marché forain de Saint-Paul | REUNION | Combava en vente sur le marché forain de Saint Paul (La Réunion).jpg | Marie-angele.joly | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Combava_en_vente_sur_le_march%C3%A9_forain_de_Saint_Paul_(La_R%C3%A9union).jpg |
| 40 | Plage de Ti Sable | REUNION | La plage de Ti Sable à Saint-Joseph.jpg | Clémenceau Lauret | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:La_plage_de_Ti_Sable_%C3%A0_Saint-Joseph.jpg |
| 41 | Anse Grosse Roche | MARTINIQUE | Anse Grosse Roche, le Marin.jpg | Sapakagadewmoinjadiw | CC-BY-SA-4.0 | https://commons.wikimedia.org/wiki/File:Anse%20Grosse%20Roche%2C%20le%20Marin.jpg |
## Notes
- Les URLs utilisées dans `lieux.json` sont de la forme `https://commons.wikimedia.org/wiki/Special:FilePath/<FICHIER>?width=1200`
(redimensionnement à 1200 px de large assuré par Wikimedia).
- Photos « domaine public » : *La Pelée vue du Carbet.jpg* (Jurassi), *ILES et BAGNE 037.JPG* (davric), *Piton des Neiges1.JPG* (Dunog).
- Photos CC0 (pas d'attribution requise, auteur crédité par courtoisie) : les deux clichés de Thérèse Gaigé (Anse Dufour, Anse Noire).
## Images Mapillary — mode street « An lari a »
Les 20 images du corpus `app/src/lib/server/data/street.json` sont servies par la plateforme
Mapillary via la visionneuse mapillary-js (licence MIT). Chaque image reste la propriété de son
auteur et est publiée sous **CC BY-SA 4.0** (contributeurs Mapillary) — vérifiée via l'API Mapillary
(`creator.username`) par `app/scripts/validate-street.mjs`. Attribution affichée dans le jeu :
« © <auteur> / Mapillary (CC BY-SA 4.0) » + logo Mapillary intégré à la visionneuse.
| # | Lieu | Région | Image Mapillary | Auteur | Date de capture | 360° |
|---|------|--------|-----------------|--------|-----------------|------|
| 1 | Rue Laurence Valmy, Pointe-à-Pitre | GUADELOUPE | [2941939632687980](https://www.mapillary.com/app/?pKey=2941939632687980) | cartophyl | 2015-07-07 | non |
| 2 | Rue Achille René Boisneuf, Les Abymes | GUADELOUPE | [306781020957650](https://www.mapillary.com/app/?pKey=306781020957650) | ratzillas | 2015-07-17 | non |
| 3 | Place Renovation le Bourg, Le Gosier | GUADELOUPE | [919062132219342](https://www.mapillary.com/app/?pKey=919062132219342) | kaartcam | 2016-01-02 | non |
| 4 | Rue Emmanuel Robinet, Sainte-Anne | GUADELOUPE | [956408765176680](https://www.mapillary.com/app/?pKey=956408765176680) | ratzillas | 2019-07-15 | oui |
| 5 | Route des Esclaves, Basse-Terre | GUADELOUPE | [212605717097536](https://www.mapillary.com/app/?pKey=212605717097536) | kaartcam | 2016-01-04 | non |
| 6 | Rue Victor Sévère, Fort-de-France | MARTINIQUE | [152801196814796](https://www.mapillary.com/app/?pKey=152801196814796) | kaartcam | 2015-12-31 | non |
| 7 | Rue des Barrières, Le Lamentin | MARTINIQUE | [1120779875836768](https://www.mapillary.com/app/?pKey=1120779875836768) | Caramel | 2024-04-29 | oui |
| 8 | Rue Gabriel Péri, Saint-Pierre | MARTINIQUE | [1299527321706804](https://www.mapillary.com/app/?pKey=1299527321706804) | jeremylavarenne | 2025-08-31 | non |
| 9 | Rue Florent Holo, Le François | MARTINIQUE | [4102521129805870](https://www.mapillary.com/app/?pKey=4102521129805870) | kaartcam | 2016-01-01 | non |
| 10 | Passage des Fleurs, Sainte-Marie | MARTINIQUE | [131479329019761](https://www.mapillary.com/app/?pKey=131479329019761) | kaartcam | 2015-12-31 | non |
| 11 | Rue Francois Arago, Cayenne | GUYANE | [259270559222687](https://www.mapillary.com/app/?pKey=259270559222687) | kaartcam | 2016-08-18 | non |
| 12 | Rue de lOdéon, Kourou | GUYANE | [198127629404270](https://www.mapillary.com/app/?pKey=198127629404270) | hacp | 2022-09-07 | non |
| 13 | Avenue Albert Sarraut, Saint-Laurent-du-Maroni | GUYANE | [147142287390967](https://www.mapillary.com/app/?pKey=147142287390967) | pma | 2021-01-18 | non |
| 14 | Rue Maurice BOCS, Matoury | GUYANE | [582210316504280](https://www.mapillary.com/app/?pKey=582210316504280) | kaartcam | 2016-08-18 | non |
| 15 | Rue de la CANNE À SUCRE, Remire-Montjoly | GUYANE | [247810083801809](https://www.mapillary.com/app/?pKey=247810083801809) | kaartcam | 2016-08-18 | non |
| 16 | Rue de Paris, Saint-Denis | REUNION | [2262788723930767](https://www.mapillary.com/app/?pKey=2262788723930767) | AllWays360 | 2022-10-06 | oui |
| 17 | Rue du Cimetiere, Saint-Pierre | REUNION | [143202321798356](https://www.mapillary.com/app/?pKey=143202321798356) | sigstpierre | 2022-11-09 | oui |
| 18 | Rue Aristide Briand, Le Tampon | REUNION | [1382811445417165](https://www.mapillary.com/app/?pKey=1382811445417165) | vandecasteele | 2019-12-16 | non |
| 19 | Rue Elie Eudor, Saint-Paul | REUNION | [928324514646684](https://www.mapillary.com/app/?pKey=928324514646684) | sogefi | 2018-10-14 | non |
| 20 | Ccal de la Republique, Saint-André | REUNION | [519625869420978](https://www.mapillary.com/app/?pKey=519625869420978) | vandecasteele | 2019-06-28 | oui |
-40
View File
@@ -1,40 +0,0 @@
body {
margin: 0;
padding: 0;
font-size: 18px; /* Taille de base pour les grands écrans */
}
h1 {
font-size: 24px; /* Taille de base pour les titres sur les grands écrans */
margin: 0.5em;
}
ul {
list-style-type: none;
padding: 1em;
}
li {
margin-bottom: 10px;
}
a {
text-decoration: none;
color: #1F51FF;
font-weight: bold;
}
/* Requêtes média pour les écrans de moins de 600px de large */
@media (max-width: 600px) {
body {
font-size: 8vw; /* Augmente la taille de la police sur les petits écrans */
}
h1 {
font-size: 5.5vw; /* Augmente la taille de la police des titres sur les petits écrans */
}
ul, li {
padding: 3vw; /* Augmente le padding pour plus d'espace */
}
}
-81
View File
@@ -1,81 +0,0 @@
#back-button {
margin-left: 1em;
cursor: pointer;
}
body {
margin: 0;
padding: 0;
}
html, body, #map {
height: 90%;
}
#chrono {
font-weight: bold;
margin-top: 1em;
text-transform: uppercase;
}
.game-button {
background-color: #3498db;
border: 2px solid #3498db;
border-radius: 5px;
color: #fff;
cursor: pointer;
font-size: 15px;
margin-bottom: .3em;
padding: 8px 15px;
transition: all 0.3s ease;
}
.game-button:hover {
background-color: #2980b9;
border-color: #2980b9;
}
.game-button:disabled {
background-color: #d8d8d8;
border-color: #d8d8d8;
cursor: not-allowed;
}
#title,div {
text-align: center;
}
#penalty {
opacity: 1;
transition: opacity 1s ease;
}
.popup-ko .maplibregl-popup-content {
background-color: rgba(255, 0, 0, 0.9);
border-radius: 10px;
box-shadow: 0px 0px 0px 2px rgb(0, 0, 0);
}
.popup-ok .maplibregl-popup-content {
background-color: rgba(0, 255, 34, 0.9);
border-radius: 10px;
box-shadow: 0px 0px 0px 2px rgb(0, 0, 0);
}
.maplibregl-popup-tip {
display: none !important;
}
@media (max-width: 600px) {
body {
font-size: 100%;
}
h1 {
font-size: 5.5vw;
}
ul, li {
padding: 3vw;
}
}
+124
View File
@@ -0,0 +1,124 @@
# JWE v2 — Décisions d'architecture (Agent Architecte)
Date : 2026-07-16 · Mission : refonte GeoGuessr souverain (voir `projet_geoguessr_97x.md`)
## 1. Décision back-end : SvelteKit seul (pas de Strapi)
**Décision : SvelteKit seul, avec les lieux dans un fichier JSON versionné dans Git.**
Arguments :
- **Frugalité OKI** : un seul processus Node à héberger, pas de CMS + admin + DB à maintenir, pas de surface d'attaque supplémentaire. SQLite serait de toute façon peu utile pour un corpus de ~40 lieux statiques.
- **Critère du prompt** (« qui ajoute les lieux ? ») : le corpus est éditorial, produit par l'Agent Contenu et relu. Le workflow Git (pull request = relecture + crédits photos vérifiés) est la modération. Le `docs/contribution.md` documente l'ajout d'un lieu par PR.
- **Livrables finaux** : le guide de déploiement demandé est « SvelteKit + Tile Server » — Strapi n'y figure pas.
- **Anti-triche** : le JSON reste côté serveur (`src/lib/server/`), jamais importé par le client ; les endpoints filtrent les champs. Impossible de faire plus simple.
Si un jour des contributeurs non-dev doivent saisir des lieux en masse, la porte vers Strapi reste ouverte (le schéma JSON est le content-type tout désigné), mais ce n'est pas le besoin actuel.
## 2. Architecture des tiles MapLibre
- **Rendu** : MapLibre GL JS (verrouillé), chargé en lazy (import dynamique uniquement sur les écrans de jeu / exploration).
- **Dev / démo** : tiles vectorielles [OpenFreeMap](https://openfreemap.org) — libres, basées OpenStreetMap, sans clé API. Style **custom OKI** (JSON de style propre, dérivé du style Positron, re-teinté : mer bleu profond caraïbe, terre sable, végétation verte dense, labels sobres — pas le « bleu Google »).
- **Prod auto-hébergée** : `tileserver-gl` + extraits `.mbtiles` OpenStreetMap des 4 régions (Guadeloupe, Martinique, Guyane, La Réunion — quelques dizaines de Mo au total). Procédure dans `docs/deploiement.md`. Le style OKI accepte l'URL des tiles par variable d'environnement (`PUBLIC_TILES_URL`), bascule sans changement de code.
- **Contrainte géographique** : `maxBounds` = enveloppe union des 4 régions (≈ lon 63…57, lat 23…18) + `minZoom`, donc impossible de scroller en Europe/Amérique du Nord. 4 boutons « saut de région » (GUADELOUPE / MARTINIQUE / GUYANE / RÉUNION) replacent la vue sur la région. Limite connue : l'enveloppe rectangulaire inclut l'Atlantique tropical et le Brésil — inoffensif (aucun indice sur le lieu), documenté.
- Attribution © OpenStreetMap contributors affichée.
## 3. Stratégie Wikipedia / Wikidata
Principe : **rien de stocké en base**, interroge l'API en temps réel avec cache court, côté serveur uniquement.
Endpoint serveur : `GET /api/wiki/[qid]` (ex. `Q3077840` = Fort Delgrès — l'exemple `Q2216838` du prompt initial était erroné, corrigé par l'Agent Contenu)
1. `wbgetentities` sur `www.wikidata.org` → récupère le `sitelink` frwiki (et le libellé fr en fallback). **Fallback de langue : fr uniquement** — décision d'audit (A3) : pas de repli sur enwiki, on préfère l'appel à contribution qu'une redirection silencieuse vers l'anglais.
2. `GET https://fr.wikipedia.org/api/rest_v1/page/summary/{titre}``title`, `extract`, `content_urls`, `thumbnail`.
3. Réponse normalisée : `{ qid, title, extract, url, thumbnail, description }`.
4. QID sans sitelink frwiki → `404 {"reason":"no-frwiki"}` (cas intermédiaire, A3) : le front affiche la **variante Cas B « Pwen blindé — Pa nyen an fransé »** (la fiche Wikidata existe, l'article français reste à traduire/créer ; CTA recherche pré-remplie + lien vers la fiche Wikidata). `wikidata_id` null côté lieu → Cas B « lacune totale » inchangé.
5. **Cache** : `Map` en mémoire, TTL 24 h + `Cache-Control: max-age=86400`. User-Agent explicite (`JWE-OKI/x.y (contact)`) comme demandé par la politique Wikimédia.
## 4. Arborescence du projet
```
JWE/ (dépôt existant — l'ancien PHP est conservé tel quel)
├── app/ ← nouvelle application SvelteKit 2 / Svelte 5
│ ├── src/
│ │ ├── lib/
│ │ │ ├── server/
│ │ │ │ ├── lieux.ts (accès données + sélection aléatoire + scoring)
│ │ │ │ └── data/lieux.json (corpus 40 lieux — serveur uniquement)
│ │ │ ├── components/ (GameMap, PhotoPanel, ResultPanel, ScoreCard…)
│ │ │ ├── i18n/ (fr.ts, gcf.ts, store)
│ │ │ ├── styles/oki.css (tokens couleurs OKI)
│ │ │ └── utils/ (score.ts, geo.ts)
│ │ ├── routes/
│ │ │ ├── +layout.svelte (header, switch langue FR/CR)
│ │ │ ├── +page.svelte (accueil : 4 régions, modes, Jouer)
│ │ │ ├── jeu/[mode]/ (écran de jeu split photo/carte)
│ │ │ ├── explorer/ (mode Aprann : carte pleine page)
│ │ │ └── api/
│ │ │ ├── round/+server.ts (GET : lieu aléatoire SANITISÉ)
│ │ │ ├── photo/[id]/+server.ts (GET : proxy photo sharp → WebP, sans EXIF, cache 24 h)
│ │ │ ├── guess/+server.ts (POST : {placeId, lat, lon, hints, timeMs} → score + vérité)
│ │ │ ├── lieux/+server.ts (GET : catalogue sanitise pour Explorer, SANS id)
│ │ │ └── wiki/[qid]/+server.ts (GET : extrait Wikipedia, cache 24 h)
│ │ ├── app.html / app.d.ts
│ │ └── service-worker.ts (PWA)
│ ├── static/ (manifest.webmanifest, icônes, photos éventuelles)
│ └── package.json / svelte.config.js / vite.config.ts
├── docs/ (architecture, déploiement, contribution, audit)
├── content/ (sources de travail de l'Agent Contenu : crédits photos)
└── projet_geoguessr_97x.md
```
## 5. Spécifications API REST (anti-triche)
| Endpoint | Méthode | Payload | Réponse |
|---|---|---|---|
| `/api/round?region=&mode=&exclude=` | GET | — | `{ id, nom, nom_creole, categorie, difficulte, photo{url,credit,alt,srcset}, indices[] }`**jamais** `coordonnees`, `commune`, `region`, `wikidata_id`. `photo.url` = `/api/photo/<uuid>` (opaque, proxy serveur — C4) + `photo.srcset` `{ "400", "800", "1200" }` |
| `/api/photo/[id]?w=` | GET | `w` ∈ {400, 800, 1200} (défaut 1200) | `image/webp` retraitée (sharp : rotation auto, métadonnées EXIF/GPS supprimées), `Cache-Control: public, max-age=86400, immutable`, cache mémoire 24 h. 404 si id inconnu, 400 si `w` invalide. Fetch amont = URL Commons du corpus uniquement (pas de proxy ouvert) |
| `/api/guess` | POST | `{ id, lat, lon, hintsUsed, timeMs? }` | `{ distanceKm, score, radiusEffKm, coordonnees, commune, region, nom, wikidata_id }` |
| `/api/lieux` | GET | — | Catalogue sanitise pour Explorer (coords arrondies à 0.05°, mode sans score). **Sans `id`** (anti-corrélation round → commune, C4) ; photos en URLs Commons directes (mode sans enjeu) |
| `/api/wiki/[qid]` | GET | — | `{ title, extract, url, thumbnail }`, `Cache-Control: max-age=86400` ; `404 {"reason":"no-frwiki"}` si QID sans article frwiki |
Règles :
- Le scoring est **recalculé côté serveur** : `score = round(5000 × e^(d/r_eff))` avec `r_eff = max(r_difficulté, sqrt(aire_commune_km2 / π))` quand le champ optionnel `aire_commune_km2` est renseigné (A1 — équité Guyane : communes immenses), sinon `r_difficulté` seul (50/15/5/1 km). Pénalité 10 %/indice, bonus temps ≤ +20 % plafonné à 5000. `radiusEffKm` (0,1 km) est renvoyé pour transparence.
- Distance : haversine.
- Le client ne reçoit la vérité (coordonnées, commune, wikidata_id) **qu'après** la soumission du marqueur.
- `exclude` : liste d'ids déjà joués (mode Défi 5 rounds, stateless — pas de session serveur nécessaire, pas de leaderboard).
## 6. Décisions annexes
- **Adapter** : `adapter-node` (auto-hébergement sobre derrière nginx/caddy).
- **PWA** : manifest + service worker minimal (cache app shell, photos en stale-while-revalidate).
- **i18n** : dictionnaires maison `fr` / `gcf` (créole), store Svelte, `lang` persistée en localStorage.
- **Photos** : en mode jeu, **proxy serveur `/api/photo/[id]`** (C4 — l'URL Wikimedia Commons contient le nom du fichier, souvent un spoiler, et les EXIF peuvent embarquer du GPS) : le serveur fetch l'URL Commons du corpus, retraite avec **sharp** (rotation auto, suppression de toutes les métadonnées par défaut, WebP, largeurs 400/800/1200), cache mémoire 24 h + `Cache-Control: immutable`. `PhotoPanel` utilise `<img src srcset sizes>`. L'Explorer (`/api/lieux`) garde les URLs Commons directes (mode sans enjeu) et le service worker met en cache les deux origines.
- **A11y / calm tech** : `prefers-reduced-motion` respecté (pas de vol de marqueur), timer informatif non anxiogène, navigation clavier (carte : flèches déplacent le marqueur, Entrée valide).
- **Licence code** : MIT (le dépôt historique était AGPL — la refonte est un nouveau module `app/` sous MIT comme exigé par le prompt ; le `LICENSE` racine reste l'historique, un `app/LICENSE` MIT est ajouté).
## 7. Correctifs d'audit (2026-07-17)
- **C4 — URLs photo spoiler** : voir §6 « Photos » et §5. Deux fuites colmatées : le nom de fichier Commons dans `photo.url` (remplacé par le proxy opaque `/api/photo/<uuid>`) et la corrélation `id` round ↔ `id` catalogue (`/api/lieux` n'expose plus d'`id` ; l'Explorer utilise des indices éphémères côté client).
- **A1 — Radius de score en Guyane** : voir §5 « Règles ». `aire_commune_km2` (champ optionnel du schéma) élargit le rayon effectif : `sqrt(aire/π)`. Test de référence : Saint-Laurent-du-Maroni (4320,8 km², EXPERT), guess à 40 km → `radiusEffKm` 37,1, score ≈ 1700 (au lieu de ≈ 0). Le code tolère l'absence du champ.
- **A2 — Pas de fuite de région** : la caméra initiale de `GameMap` est **globale** (`center: [-58, 0]`, `zoom: 3.6` — vue d'ensemble des 4 régions, aucun indice sur le lieu). Les 4 boutons région sont la **devinette en deux temps** : étape 1 = sauter vers la région supposée, étape 2 = poser le marqueur. Les deux étapes sont combinées par la distance seule : mauvaise région → distance énorme → score ≈ 0. Aucune donnée serveur ne révèle la région avant le guess (`/api/round` ne l'inclut pas).
- **A3 — Chaîne Wikipedia** : voir §3. `Cache-Control: max-age=86400` ; cas intermédiaire QID sans frwiki → `404 {"reason":"no-frwiki"}` → variante Cas B dédiée côté front ; fallback de langue fr uniquement, documenté dans le code.
## 8. Phase 2 (2026-07-17) — ADR-001 v1 et ADR-002
- **ADR-001 v1 — Défi par lien à seed** (`/defi/<seed>`) : `src/lib/server/tirage.ts` (hash cyrb53 → PRNG mulberry32, Fisher-Yates déterministe, contraintes ≥1 MONUMENT / ≥1 LIEU / ≥2 régions par échanges déterministes — zéro `Math.random`, déterminisme inter-machines). `GET /api/defi/[seed]` → 5 rounds sanitisés identiques pour tous (`no-store`, seed alphanumérique 440). Accueil : « Créer un lien de défi » (seed 8 chars sans ambiguïté). Bilan : « Copier le lien du défi ». La comparaison des scores reste humaine (image canvas) — zéro compte, zéro état serveur, zéro leaderboard. La v2 temps réel (PlaySocketJS) reste conditionnée au gate de traction de l'ADR (≥30 parties/sem. ×4 sem. + ≥5 demandes explicites).
- **ADR-002 — Carte SVG légère hors-jeu** : pipeline `app/scripts/build-carte-regions.mjs` (geo.api.gouv.fr → mapshaper 7 % → `src/lib/map/regions-geo.json`, 91,8 KB gz ≤ 150 KB) ; composant `CarteRegions.svelte` from scratch (SVG, projection équirectangulaire par inset, 2×2 responsive, `<button>` par région avec `aria-label` FR/créole, SSR sans JS, prop `marqueurs` pour le récap guess→réel, attribution © OSM/données publiques). Utilisée sur l'accueil (sélection de région) et les bilans défi — MapLibre reste strictement aux écrans de jeu (devinette, résultat, explorer). Attribution : contours © geo.api.gouv.fr / données publiques.
## 9. Correctif UX résultat (2026-07-17)
- **Carte résultat façon GeoGuessr** : à la révélation, le marqueur du joueur **reste à sa position** (corail) et la position réelle apparaît (vert), reliées par une ligne pointillée avec **étiquette de distance au milieu** (`distanceKm`) ; la carte cadre les deux points (`fitBounds`, instantané si `prefers-reduced-motion`). Remplace l'ancien « vol » du marqueur vers la position réelle, qui détruisait la comparaison visuelle. Prop `distanceKm` ajoutée à `GameMap` (alimentée par la réponse serveur, jamais calculée côté client).
## 10. ADR-003 — Mode street « An lari a » via Mapillary (2026-07-18)
5e mode de jeu : le joueur voit une **photo street-level navigable** (visionneuse Mapillary) au lieu d'une photo statique, et devine la commune. Mécanique carte + guess + score **inchangée**.
- **Pourquoi Mapillary** : seule source de street-level imagery couvrant correctement les 4 régions (bonne couverture Gwada/Martinique/Réunion, littoral guyanais) ; images **CC BY-SA 4.0**, lib `mapillary-js` **MIT**, API gratuite (token client requis, rate-limité par app). **Exception documentée** à « zéro service tiers » (Mapillary = plateforme Meta), limitée à ce mode ; alternative souveraine future = Panoramax (reco R4 audit passe 2), couverture DOM encore insuffisante à cette date.
- **Corpus curé, pas de tirage aléatoire dans l'API** : `app/src/lib/server/data/street.json` (20 lieux, 5/région), produit par `app/scripts/curate-street.mjs` (bbox < 0,01° ou grille de recherches par rayon autour de la **mairie** — le centroïde geo.api tombe souvent hors du centre-ville ; tri qualité/récence, préférence 360°), revérifié par `app/scripts/validate-street.mjs` (image existe, `computed_geometry` < 100 m, crédit auteur, sitelink frwiki). La vérité terrain (`coordonnees`) est **figée** dans le corpus (dérive possible de `computed_geometry` côté Mapillary).
- **Phase éducative par commune** : `wikidata_id` = QID de la **commune** (un coin de rue n'a pas vocation à avoir sa page) → `WikiFiche` réutilisé tel quel, aucune variante Cas B nouvelle. `aire_commune_km2` renseigné (équité Guyane, A1).
- **Anti-triche** : `/api/round?mode=street` + `sanitizeRoundStreet()` — seuls `id, nom, nom_creole, categorie, difficulte, mapillaryId, credit, indices` partent ; coords/commune/région/wikidata_id jamais avant le guess. **Limitation assumée** : l'`image_key` est publique (la visionneuse appelle Mapillary depuis le navigateur) → un joueur techniquement équipé peut retrouver la position via l'API Mapillary (même propriété que GeoGuessr/Street View ; acceptable en solo sans leaderboard). La visionneuse n'affiche **pas de carte** (mapillary-js n'en a pas par défaut), donc aucun spoiler visuel.
- **Visionneuse** : `StreetPanel.svelte`, lazy load façon MapLibre (`import('mapillary-js')` + CSS — chunk séparé ~1 MB, 0 occurrence dans le bundle initial), `component.cover: false`, `moveTo()` avec état d'erreur (image retirée → message + round suivant possible). Token `PUBLIC_MAPILLARY_TOKEN` via `$env/dynamic/public` (pattern `PUBLIC_TILES_URL`) : **token client**, conçu par Mapillary pour être exposé côté navigateur.
- **Réutilisation sans modification** : `GameMap`, `ResultPanel`, `WikiFiche`, scoring (`scoreGuess`/`skipResult` acceptent `Lieu | StreetLieu`), timer, indices, bouton « Passer ». `RoundPlace.photo` devient optionnel (`mapillaryId`/`credit` ajoutés) ; lookup unifié `getLieuById` (2 corpus) pour `/api/guess`, `getLieuPhotoById` conservé pour le défi et le proxy photo.
- **Hors scope v1** : street dans `/defi/[seed]` et `/explorer`, cache SW des tuiles Mapillary (les requêtes `graph.mapillary.com`/FBCDN passent en direct).
+176
View File
@@ -0,0 +1,176 @@
# Audit OKI — JWE v2 (Agent Intégration & QA)
Date : 2026-07-17 · Périmètre : `app/` (SvelteKit 2 + Svelte 5 + MapLibre GL 5)
Méthode : tests **réellement exécutés** sur le build de production (`node build`, PORT=4173) + revue de code. Chaque point est accompagné de sa preuve (commande, extrait).
Légende : ✅ conforme · ⚠️ conforme avec réserve / point d'amélioration · ❌ non conforme
---
## 1. Build et vérifications statiques
| Test | Résultat | Preuve |
|---|---|---|
| `npm run check` | ✅ | `svelte-check found 0 errors and 0 warnings` |
| `npm run build` | ✅ | `✓ built in 5.05s` + `adapter-node ✔ done` |
### Isolation de MapLibre (bundle initial)
- Le chunk MapLibre `xnoNZPIh.js` (**1031 KB brut / 277,8 KB gzip**) n'est chargé que par `import("./xnoNZPIh.js")` **dynamique** depuis le chunk de `GameMap` — vérifié par `grep` dans `build/client/_app/immutable/`.
- Le HTML SSR de `/` (5,6 KB) ne contient **0 occurrence** de « maplibre » et ne bootstrap que `entry/app.js` + `entry/start.js`.
- Le CSS MapLibre (`maplibre-gl.*.css`, 68,3 KB / 9,8 KB gz) est un asset séparé, chargé par le même import dynamique (`GameMap.svelte:279`).
**✅ Le bundle initial ne contient pas MapLibre.**
---
## 2. API — tests fonctionnels (serveur `node build`, PORT=4173)
### 2.1 Anti-triche `/api/round` ✅
15 tirages variés (sans filtre, `region`, `region+categorie`, `categorie`, `region+categorie+exclude` avec 2 ids exclus) :
```
15/15 tirages : AUCUNE fuite (clés coordonnees/commune/region/wikidata_id absentes)
```
Payload conforme à `docs/architecture.md` §5 : `{ id, nom, nom_creole, categorie, difficulte, photo{url,credit,alt}, indices[] }`. `Cache-Control: no-store` présent. Les filtres sont respectés (ex. `region=REUNION&categorie=LIEU` → Piton de la Fournaise).
*Note : le `nom` du lieu est dans le payload — c'est le choix de la spec (§5), pas une fuite : le jeu nomme le monument à reconnaître.*
### 2.2 Partie complète + cohérence du score ✅
Scénario réel : `GET /api/round?region=GUADELOUPE` → Jardin botanique de Deshaies (DIFFICILE, r=5 km) → `POST /api/guess` avec coords fausses :
- Réponse : `distanceKm: 38.5, score: 2` — recalcul indépendant haversine + `round(5000·e^(38.5/5))` = **2** → écart 0.
- Second test (Fort Delgrès, MOYEN, guess à 10,0 km, `hintsUsed: 1`, `timeMs: 30000`) : serveur **2540**, recalcul `min(5000, 2572×0,9 + 2572×0,9×0,2×0,5)` = **2540** → écart 0. Pénalité 10 %/indice et bonus temps ≤ +20 % conformes.
- `skip: true``score: 0, distanceKm: null`, vérité révélée (extension documentée, cohérente avec le bouton « Passer »).
- Erreurs : id inconnu → **404**, coords invalides → **400**, id manquant → **400**, JSON invalide → **400**.
### 2.3 Cas A — lieu avec `wikidata_id` ✅
| Lieu | `/api/guess` | `/api/wiki/{qid}` |
|---|---|---|
| Fort Delgrès | `wikidata_id: "Q3077840"` | 200, `title: "Fort Delgrès"`, extrait FR **422 car.**, `url: https://fr.wikipedia.org/wiki/Fort_Delgr%C3%A8s` |
| Centre spatial guyanais | `wikidata_id: "Q308987"` | 200, extrait FR **447 car.**, url fr.wikipedia |
Cache : `cache-control: public, max-age=3600` vérifié par `curl -I` ; cache mémoire TTL 24 h + User-Agent Wikimédia explicite dans `routes/api/wiki/[qid]/+server.ts`.
### 2.4 Cas B — lacune documentaire (CRUCIAL) ✅
Corpus : **9 lieux `wikidata_id: null`** (2 GP, 2 MQ, 3 GUY, 2 REU) — intentionnels, conformes au piège de la spec §Agent Contenu.
- `POST /api/guess` sur **Plage de Bois Jolan** (`ff00fd1d…`) et **Anse Noire** (`cd652fb7…`) → `wikidata_id: null` dans les deux réponses. ✅
- Rendu (`WikiFiche.svelte:64-78`) : `wikidataId` null → panneau **`.cas-b`** visuellement distinct (fond `--oki-lacune-fond` #fdf3e3, bordure 2px `--oki-lacune-bord` #d9a441, icône ◌ en pointillés) vs `.cas-a` vert doux. ✅
- Titre exact de la spec : **« Pwen blindé — Sa pa dokimanté »** (`fr.ts:68`, `gcf.ts:70`). ✅
- Texte FR conforme à §4.3 (« Ce lieu existe, mais il n'a pas de page sur Wikipédia ni de fiche sur Wikidata… qui alimentent même l'intelligence artificielle). ») + équivalent créole complet dans `gcf.ts:71-72`. ✅
- CTA **« Kontribyé sou Wikipédia »** → `https://fr.wikipedia.org/w/index.php?search={nom du lieu}&title=Spécial:Recherche` — titre du lieu pré-rempli dans la recherche (`WikiFiche.svelte:38-40`) + lien secondaire vers le guide « Premiers pas ». ✅
- **Chemin « qid non null mais wiki 404 »** : `/api/wiki/Q15646372` (entité sans sitelink fr) → **404** ; dans `WikiFiche.svelte:28`, `res.ok ? … : null`**bascule bien sur le panneau Cas B** (même comportement sur erreur réseau, ligne 29-30). ✅
- Chaîne « Pwen blindé » présente dans le bundle client livré (`grep` dans `build/`). ✅
### 2.5 `/api/lieux` ✅
40 lieux ; toutes les coords sont des **multiples exacts de 0,05** (vérifié par script, ex. Fort Delgrès → `{lat: 16, lon: -61.7}`). `Cache-Control: public, max-age=300`.
### 2.6 Pages ✅
`/` 200 · `/jeu/monument` 200 · `/jeu/lieu` 200 · `/jeu/defi` 200 · `/explorer` 200 · `/manifest.webmanifest` 200 · `/service-worker.js` 200 · `/icon.svg` 200 · `/jeu/triche`**404** (mode invalide rejeté).
SSR vérifié : le HTML de `/` contient `<h1>JWE</h1>` rendu serveur (contenu visible avant hydratation).
---
## 3. Parité i18n FR / créole ✅
Script Node comparant les clés aplaties de `fr.ts` et `gcf.ts` :
```
clés fr : 77 | clés gcf : 77
manquantes dans gcf : aucune — manquantes dans fr : aucune
```
Le message de lacune existe dans les DEUX langues (titre, texte, CTA, guide). Double garantie : `gcf` est typé `Dict` (`gcf.ts:3`), donc toute clé manquante casserait `npm run check`. L'attribut `<html lang>` est mis à jour au changement de langue (`store.svelte.ts:25`).
---
## 4. A11y / doctrine OKI (revue de code)
| Point | Verdict | Preuve |
|---|---|---|
| `prefers-reduced-motion` | ✅ | Règle globale `oki.css:111-117` ; vol du marqueur désactivé (`GameMap.svelte:56-57,116-117`) et transitions cartes à `duration: 0` ; transition du bottom-sheet coupée (`explorer/+page.svelte:256-260`) |
| Navigation clavier carte | ✅ | Zone carte `role="application"`, `tabindex="0"`, `aria-label` i18n ; flèches = déplacer le marqueur (pas constant en pixels), Entrée = valider (`GameMap.svelte:246-273`) ; focus-visible visible (`oki.css:67-72`) |
| Une seule action primaire / écran | ⚠️ | Accueil : « Jouer » seul corail. Jeu : « Valider » seul corail (Passer = secondaire, Indice = tertiaire). Bilan : « Partager » seul. **Réserve** : écran résultat Cas B = bouton corail « Lieu suivant » **+** CTA orange « Kontribyé sou Wikipédia » — deux éléments fortement colorés. Cohérent avec Peak-End (§5), mais en tension avec « une seule action primaire ». À trancher en design review. |
| Bouton Valider en zone pouce | ✅ | `.barre-actions` sticky en bas + `env(safe-area-inset-bottom)` (`jeu/[mode]/+page.svelte:374-384`) ; accueil : `.zone-pouce` fixe bas |
| Timer non anxiogène | ✅ | `TimerRing` : cercle qui se vide, couleur douce `--oki-vert-clair`, **aucun chiffre**, **aucune échéance** (à 0 le tour continue, le bonus s'arrête juste) ; timer désactivé par défaut |
| Pas de mécanique dopaminergique | ✅ | `grep -i 'streak|leaderboard|classement|loot|confetti'` → 0 résultat ; pas de session serveur, pas de compte, « Passer » = 0 point sans pénalité, ton encourageant (« Kité sa ye ? ») |
| Zoom contraint aux 4 régions | ✅ | `maxBounds` [-63,-23,57,18] + `minZoom: 4` (`regions.ts`) + 4 boutons « saut de région » avec `aria-label` groupe |
| Photos | ✅ | `loading="lazy" decoding="async"` partout (`PhotoPanel`, `explorer`, `WikiFiche`) ; `alt` descriptif du corpus ; crédit affiché sous chaque photo |
---
## 5. Performance 4G (mesures build + estimation)
Pas de Lighthouse disponible dans l'environnement → mesures réelles des artefacts + estimation argumentée.
### Poids mesuré (sur fil, gzip — les `.gz` sont pré-générés dans le build)
| Écran | Détail | Poids |
|---|---|---|
| **Premier écran `/`** | HTML 5,6 KB + JS initial 38,7 KB gz + CSS 1,8 KB gz | **≈ 43 KB** |
| `/jeu/*` (supplément) | code page + GameMap | +12,9 KB gz |
| MapLibre (lazy, uniquement écrans carte) | JS 277,8 KB gz + CSS 9,8 KB gz | 287,6 KB gz |
| Photos | Wikimedia `?width=1200`, lazy | ~150-400 KB/photo |
### Estimation 4G caribéen (≈ 10 Mbps, RTT 150 ms ; et slow 4G 1,6 Mbps)
- **Premier écran < 3 s : ✅ large.** ~43 KB → < 0,5 s de transfert même en slow 4G ; SSR → `<h1>` et grille des régions visibles avant hydratation ; police système (aucune webfont) ; zéro requête tierce.
- Écran de jeu : +300 KB gz (MapLibre) ≈ 1,5-2 s en slow 4G, chargé **après** l'affichage de la photo (lazy) — le joueur peut déjà observer la photo.
- PWA : app shell pré-caché par le service worker → 2e visite quasi instantanée, photos en stale-while-revalidate.
---
## 6. Checklist d'audit OKI (spec §Agent Intégration & QA)
- [x] **Une seule action primaire par écran** — ✅ (⚠️ réserve Cas B, voir §4)
- [x] **Mobile : bouton Valider en zone du pouce, carte utilisable au doigt** — ✅ (sticky bottom, marqueur draggable, boutons zoom +/- visibles)
- [x] **Performance : premier écran < 3 s, MapLibre lazy-loadé** — ✅ (~43 KB gz initial, chunk MapLibre dynamique)
- [x] **Éthique : pas de mécanique dopaminergique, score non punitif** — ✅
- [x] **Éducation : les deux cas (Wiki OK / Wiki manquant) fonctionnent et sont distincts visuellement** — ✅ (tests §2.3/§2.4, panneaux `.cas-a` vert / `.cas-b` sable-orangé)
- [x] **Bilinguisme FR/créole présent (y compris message de lacune)** — ✅ (77/77 clés)
- [x] **PWA installable** — ✅ avec réserve : manifest + SW + icônes SVG `any`/`maskable` valides, **mais aucun PNG 192/512** — Chrome desktop peut refuser l'invite d'installation sans PNG (⚠️).
Intégration MapLibre + API Lieux + API Wikipedia : ✅. Partie complète jouée : ✅ (§2.2).
---
## 7. Bugs corrigés pendant l'audit
1. **Libellés des boutons zoom MapLibre en anglais** — Les clés i18n `carte.zoomIn`/`zoomOut` existaient mais n'étaient jamais utilisées : le `NavigationControl` natif affichait les tooltips/aria-labels anglais « Zoom in / Zoom out » sur une UI FR/créole (a11y lecteur d'écran).
- **Correctif** : `app/src/lib/components/GameMap.svelte` — option `locale` ajoutée au constructeur `new mod.Map({…})` avec `'NavigationControl.ZoomIn': t().carte.zoomIn` et `'NavigationControl.ZoomOut': t().carte.zoomOut`.
- **Vérifié** : `npm run check` 0 erreur, rebuild OK, chaîne présente dans le chunk GameMap reconstruit, serveur relancé et endpoints re-testés (200).
Aucun bug structurel trouvé.
---
## 8. Points d'amélioration restants (non bloquants)
1. ⚠️ **Icônes PWA** : ajouter des PNG 192×192 et 512×512 (certains navigateurs n'acceptent pas le SVG seul pour l'invite d'installation).
2. ⚠️ **Contraste du corail** `--oki-corail` #e4572e sur texte blanc ≈ **3,7:1** : conforme AA pour texte large et composants d'interface, juste sous les 4,5:1 du texte courant. Envisager `--oki-corail-fonce` au repos si on veut du AA strict.
3. ⚠️ **Bonus temps basé sur `timeMs` fourni par le client** (`/api/guess`) : un client modifié peut s'accorder +20 %. Sans leaderboard ni enjeu, c'est acceptable — à documenter si un mode compétitif arrive un jour.
4. ⚠️ **Deux accents forts sur l'écran résultat Cas B** (corail « Lieu suivant » + orange « Kontribyé ») : Peak-End assumé, mais à valider contre la règle « une seule action primaire ».
5. **Clés i18n inutilisées** : `resultat.bravo`, `resultat.score`, `micro.pwenBlinde`, `defi.manche` — cosmétique, à nettoyer ou brancher.
6. **Pas de tests automatisés** dans le dépôt (ni unitaires ni e2e) — les vérifications de cet audit sont manuelles ; un `vitest` sur `scoreGuess`/`sanitizeRound` + un test e2e du Cas B sécuriseraient les régressions.
7. **Limite connue** (déjà documentée dans `architecture.md`) : l'enveloppe `maxBounds` rectangulaire inclut l'Atlantique tropical et le Brésil — inoffensif.
---
## Verdict
**✅ Conforme à la spec.** Build propre, anti-triche étanche sur 15 tirages, scoring recalculé serveur et vérifié au point près, Cas A et Cas B fonctionnels (y compris le fallback 404 → Cas B), i18n FR/créole complet, doctrine OKI respectée (calm tech, zone pouce, reduced-motion, zéro dark pattern). 1 bug mineur corrigé (locale des contrôles zoom). 7 points d'amélioration non bloquants listés ci-dessus.
---
## Addendum post-audit (vérification finale orchestrateur)
- **Fix anti-spoiler** : le crédit photo (`photo.credit`, souvent explicite sur le lieu) était affiché pendant la phase de devinette. Désormais masqué pendant la devinette (`PhotoPanel`, prop `revealed`) et affiché après validation dans `ResultPanel` — attribution CC conservée, indice supprimé. Re-vérifié : `npm run check` 0 erreur, `npm run build` OK.
+56
View File
@@ -0,0 +1,56 @@
# JWE — Audit post-exécution (passe 2) — Rapport de vérification
Date : 2026-07-16 · Référentiel : `prompts/JWE-prompt-verification-agents.md` · Méthode : fetch réel, jamais recall. Corpus : 41 lieux.
## Tableau des vérifications
| ID | Vérification | Méthode / Preuve | PASS/FAIL | Correctif appliqué |
|----|--------------|------------------|-----------|--------------------|
| C1 | QID valides + sitelink frwiki | `node app/scripts/validate-lieux.mjs` : 32 QID vérifiés par `wbgetentities` batch, sitelink + label concordants | **PASS** | — |
| C2 | Les « null » sont de vrais null | Recherche `list=search` frwiki par titre exact pour les 9 nulls. **1 FAIL initial** : « Savane des Pétrifications » avait un article (casse « pétrifications » manquée au 1er contrôle) | **FAIL → PASS** | Savane → QID réel `Q3474455` (coords P625 14.4011, 60.8576, photo CC BY-SA 4.0 re-vérifiée) ; nouvelle lacune Martinique : **Anse Grosse Roche** (absence frwiki prouvée sur 4 variantes de titre, photo CC BY-SA 4.0 HTTP 200) |
| C3 | Coordonnées < 500 m de la source | Comparaison P625 ↔ JSON pour les 32 lieux à QID (haversine dans le validateur) : 32/32 < 500 m | **PASS** | Seed Fort Delgrès déjà corrigé en passe 1 (Q3077840, 15.9886, 61.7231) |
| C4a | Noms de fichiers photo opaques | Avant : URL Commons en clair dans `/api/round` (spoiler devtools). Après : `photo.url = /api/photo/<uuid>` — grep `FilePath|.jpg` sur les réponses = 0 | **FAIL → PASS** | Proxy `/api/photo/[id]?w=` (sharp : rotation, strip métadonnées, WebP, 400/800/1200, cache 24 h + `immutable`) ; `srcset` dans `PhotoPanel` ; `/api/lieux` n'expose plus `id` (anti-corrélation round↔explorer) |
| C4b | EXIF strippés | `sharp(buf).metadata()` sur `/api/photo/<id>?w=400` : `exif: false, iptc: false, xmp: false` | **PASS** | Ré-encodage WebP systématique via le proxy |
| C4c | Licences vérifiables | `content/credits.md` : 41 photos, page Commons + auteur + licence (CC-BY-SA/BY/CC0/DP uniquement) | **PASS** | — |
| C5 | Photos des lieux « null » | Les 9 nulls ont une photo Commons libre documentée (source + licence dans credits.md) — le cas « rare » du référentiel est couvert ; à terme préférer photos OKI/Panoramax | **PASS** | Recommandation R4 pour les futurs lieux |
| A1 | Score juste en Guyane | Avant : radius fixe (FAIL). Après : `radius_eff = max(radius, sqrt(aire_commune_km2/π))`, `aire_commune_km2` injecté depuis geo.api.gouv.fr (41/41 lieux). Test réel : guess à 40 km d'un lieu de Saint-Laurent-du-Maroni → `radiusEff 37,1 km`, **score 1699** (≈2 sans le fix) | **FAIL → PASS** | `lieux.ts` (`rayonEffectifKm`), réponse `/api/guess` enrichie de `radiusEffKm`, affichage discret au résultat. ⚠️ incident de revue : unités ha/1000 corrigées en ha/100 avant commit |
| A2 | Pas de fuite de région | Caméra initiale globale (`center [-58,0], zoom 3.6`, `GameMap.svelte`) — aucun zoom région automatique ; devinette en deux temps : 4 boutons région (étape 1) → marqueur (étape 2) ; combinaison par la distance (mauvaise région ⇒ score ≈ 0). Documenté dans `docs/architecture.md` §7 | **PASS** | — |
| A3 | Chaîne Wikipedia exacte | `wbgetentities(sitelinks)` → REST summary ; cache mémoire 24 h + `Cache-Control: max-age=86400` (était 3600) ; UA explicite ; fallback fr-only documenté. Cas intermédiaire tranché : 404 `{"reason":"no-frwiki"}` → variante Cas B « Pas encore d'article en français / Pa nyen an fransé » + lien fiche Wikidata | **FAIL → PASS** | `wiki/[qid]/+server.ts`, `WikiFiche.svelte`, clés `lacuneFr.*` FR+GCF ; bonus : redirections Wikidata résolues |
| A4 | Strapi vs SvelteKit | ADR §1 : SvelteKit seul + JSON versionné + script de validation au commit (`app/scripts/validate-lieux.mjs`, ajouté) | **PASS** | Script de validation livré |
| A5 | Hors scope respecté | Revue : pas de comptes, pas de leaderboard serveur, pas de multi ; scores côté client uniquement | **PASS** | — |
| B1 | Endpoint sans fuite | 15 tirages `/api/round` (passe 1) + re-test passe 2 : 0 occurrence `coordonnees/commune/wikidata_id/FilePath` | **PASS** | — |
| B2 | Score côté serveur | Le client envoie `{id, lat, lon, hintsUsed, timeMs?}` ; le serveur calcule (formule A1) ; recalculs indépendants conformes (passe 1 et 2) | **PASS** | — |
| B3 | Proxy Wikipedia | Cache 24 h + header 86400 (preuve curl `%header{cache-control}`) ; aucun texte stocké en base | **PASS** | — |
| B4 | Zéro dépendance propriétaire | `package.json` : `maplibre-gl` + `sharp` (Apache-2.0, ajouté pour C4) ; aucune clé API ; pas de télémétrie | **PASS** | — |
| F1 | Carte | Bounds + minZoom, aucune fuite région (A2), MapLibre lazy (chunk séparé, 0 occ. sur `/`), boutons zoom, clavier | **PASS** | — |
| F2 | Cas A / Cas B distincts | Panneaux visuellement distincts, message lacune FR + créole, CTA contribution pré-rempli (passe 1, revérifié passe 2) | **PASS** | — |
| F3 | Cas intermédiaire géré | 404 `no-frwiki` → variante Cas B dédiée, pas d'écran vide ni d'erreur console (chemins compilés et testés) | **PASS** | Voir A3 |
| F4 | Contour de commune | Non intégré — optionnel (« si intégré ») | N/A | Recommandation R3 |
| F5 | Doctrine OKI | Une action primaire, Valider zone pouce, timer calme, micro-interactions créoles, style non-Google | **PASS** | — |
| F6 | Perf 4G | Premier écran ≈ 43 KB gz ; photos WebP via proxy + `srcset` + lazy ; poids round hors tiles : 1 JSON (~1 KB) + 1 WebP 4001200 px | **PASS** | — |
| Q1 | Bloquants rejoués | C1, C2, A1, A2, B1, B2, F2 : preuves ci-dessus, exécutées sur `node build` (prod) | **PASS** | — |
| Q2 | Partie complète | Rounds API + résultats Cas A/Cas B/lieu guyanais testés ; rendu visuel non capturé (pas de navigateur headless dispo) | **PASS (partiel)** | Recommandation R5 |
| Q3 | Checklist OKI | Intégralement passée en passe 1 (`docs/audit-oki.md`), points inchangés | **PASS** | — |
| Q4 | Scope creep | Rien de plus que le prompt v2 (+ champs audit : `aire_commune_km2`, `radiusEffKm`, proxy photo — correctifs, pas features) | **PASS** | — |
| Q5 | CWV 4G | Mesures indirectes (poids bundles, SSR, lazy) : LCP estimé < 2 s ; pas de Lighthouse dispo | **PASS (estimé)** | Recommandation R5 |
## Recommandations (hors scope audit — pas implémentées)
| # | Priorité | Problème / opportunité | Solution proposée | Effort | Fichiers |
|---|----------|------------------------|-------------------|--------|----------|
| R1 | important | ADR-001 v1 : le Défi est aléatoire par joueur, impossible de jouer « les mêmes 5 lieux » qu'un autre | Lien à seed `/defi/<seed>` (PRNG seedé serveur, anti-fuite, partage par image) — v2 PlaySocketJS seulement si gate de traction | M | `routes/defi/[seed]`, `server/lieux.ts` |
| R2 | important | ADR-002 : MapLibre (~800 KB) absent de l'accueil, mais l'accueil n'a pas encore de carte du tout | Carte SVG statique des 4 régions (topojson geo.api.gouv.fr + mapshaper ≤ 150 KB gz, composant from scratch, sans JS) | M | `lib/map/`, `+page.svelte` |
| R3 | confort | Résultat : le joueur ne visualise pas les limites de la commune | Superposer le contour geo.api.gouv.fr (`geometry=contour`) sur la carte résultat | S | `GameMap`, `/api/guess` (code INSEE à stocker) |
| R4 | confort | Les futurs lieux « null » dépendent de Commons (rare pour les lieux non documentés) | Prévoir photos OKI propres ou Panoramax dans le guide de contribution | S | `docs/contribution.md` |
| R5 | confort | Pas de tests automatisés ni de vraies mesures Lighthouse | Vitest sur le scoring + CI légère ; Lighthouse sur le VPS de prod | M | `app/tests/` |
| R6 | confort | Icônes PWA SVG seulement ; contraste corail 3,7:1 | Générer PNG 192/512 à l'installation ; assombrir l'accent vers ≥ 4,5:1 | S | `static/`, `oki.css` |
**Verdict passe 2 : CONFORME — 0 FAIL restant.** 4 FAIL corrigés (C2, C4a, A1, A3), 1 script de validation pérenne livré.
---
## Addendum (2026-07-17) — R1 et R2 implémentées
- **R1 (ADR-001 v1)** : livrée. Déterminisme prouvé (même seed → mêmes 5 lieux, même ordre, 2 processus), anti-fuite vérifiée (0 occurrence de champ sensible dans `/api/defi/<seed>`), image de partage inchangée (score uniquement). Voir `docs/architecture.md` §8.
- **R2 (ADR-002)** : livrée. `regions-geo.json` = 91,8 KB gz (budget 150 KB) ; SSR de `/` sans MapLibre ni JS requis (4 vrais `<button>` région bilingues) ; bilans défi passés en SVG ; composant from scratch ; attribution présente. V1V5 PASS.
- Les autres recommandations (R3R6) restent ouvertes.
+87
View File
@@ -0,0 +1,87 @@
# JWE — Guide de contribution : ajouter un lieu
Le corpus de lieux vit dans `app/src/lib/server/data/lieux.json`, versionné dans Git. Ajouter un lieu = une pull request. La revue de PR sert de modération éditoriale (exactitude, crédits photo, licence).
## 1. Règles d'or d'un bon lieu
- **Photographiable et identifiable** : le lieu doit avoir une photo libre de qualité (Wikimedia Commons de préférence).
- **Localisé précisément** : coordonnées GPS au lieu près (le score Expert se joue à 1 km).
- **Éditorialement pertinent** : monument, paysage, lieu culturel, rue ordinaire… Le jeu mélange volontairement lieux célèbres et lieux du quotidien.
- **Lacunes assumées** : il est VOLONTAIRE d'inclure des lieux sans page Wikipédia (`wikidata_id: null`) — le jeu affiche alors un écran pédagogique « Pwen blindé » appelant à documenter le territoire. Mais c'est un choix, pas une négligence : vérifiez d'abord qu'aucune page/frwiki ni entité Wikidata n'existe.
## 2. Schéma du lieu
```json
{
"id": "générez un uuid (uuidgen)",
"nom": "Fort Delgrès",
"nom_creole": "Fò Delgrès",
"region": "GUADELOUPE | MARTINIQUE | GUYANE | REUNION",
"commune": "Basse-Terre",
"coordonnees": { "lat": 16.0036, "lon": -61.7319 },
"categorie": "MONUMENT | LIEU",
"difficulte": "FACILE | MOYEN | DIFFICILE | EXPERT",
"wikidata_id": "Q3077840",
"photo": {
"url": "https://commons.wikimedia.org/wiki/Special:FilePath/FICHIER?width=1200",
"credit": "© Auteur / Wikimedia Commons CC-BY-SA-4.0",
"alt": "Description précise (sert d'alternative textuelle)"
},
"indices": [
{ "niveau": 1, "texte": "Indice doux" },
{ "niveau": 2, "texte": "Indice précis" }
]
}
```
## 3. Trouver et lier l'identifiant Wikidata
1. Cherchez le lieu sur https://www.wikidata.org
2. L'identifiant ressemble à `Q3077840`.
3. Vérifiez que l'entité a un lien vers une page **fr.wikipedia** (sitelink) — c'est ce qui permet au jeu d'afficher l'extrait de l'article :
```bash
curl -s "https://www.wikidata.org/w/api.php?action=wbgetentities&ids=Q3077840&props=sitelinks&format=json" | grep frwiki
```
4. **Si le lieu n'a ni page Wikipédia ni entité Wikidata** : mettez `"wikidata_id": null`. C'est une contribution précieuse : le jeu transforme la lacune en appel à contribution. Mieux encore : créez l'entité Wikidata vous-même, puis revenez renseigner l'ID !
## 4. Choisir la photo (licence obligatoire)
1. Cherchez sur https://commons.wikimedia.org une photo nette, paysage de préférence.
2. Licences acceptées : CC BY, CC BY-SA, CC0, domaine public. **Jamais** de « fair use ».
3. Vérifiez la licence et l'auteur via l'API :
```bash
curl -s "https://commons.wikimedia.org/w/api.php?action=query&titles=File:NOM_DU_FICHIER&prop=imageinfo&iiprop=url|extmetadata&format=json"
```
4. L'URL dans le JSON utilise `Special:FilePath` avec `?width=1200` (redimensionnement à la volée côté Wikimedia — pas besoin d'héberger l'image). Testez qu'elle renvoie bien 200.
5. Reportez le crédit exact (auteur + licence) dans `photo.credit` ET dans `content/credits.md`.
## 5. Valider avant la PR
```bash
cd app
node -e "const l=require('./src/lib/server/data/lieux.json');console.log(l.length,'lieux')"
npm run check
```
Checklist de revue :
- [ ] coordonnées cohérentes avec la commune déclarée
- [ ] `wikidata_id` vérifié (ou `null` justifié)
- [ ] licence photo CC vérifiée + crédit complet
- [ ] `alt` descriptif (accessibilité)
- [ ] 2 indices progressifs, sans donner la réponse
- [ ] `nom_creole` renseigné quand la forme créole est attestée (sinon, reprendre le nom français — ne pas inventer)
## 6. Contribuer à Wikipédia / Wikidata (au-delà du jeu)
Si vous ajoutez un lieu « Pwen blindé », envisagez de documenter le lieu vous-même :
- Créer un compte et un brouillon d'article : https://fr.wikipedia.org/wiki/Aide:Brouillon
- Créer une entité Wikidata : https://www.wikidata.org/wiki/Wikidata:Main_Page
- Contacter les groupes Wikimédia locaux (Wikimédia France, groupes antillais/guyanais/réunionnais).
Chaque entité créée enrichit Wikipédia, les cartes libres… et les futurs jeux comme JWE.
+124
View File
@@ -0,0 +1,124 @@
# JWE v2 — Guide de déploiement auto-hébergé
Cible : un petit VPS (1 vCPU / 1 Go RAM suffit) sous Debian/Ubuntu, derrière nginx ou Caddy. Aucun service propriétaire, aucune clé API payante.
> **Exception documentée (mode street)** : le 5e mode « An lari a » utilise la visionneuse Mapillary (images CC BY-SA 4.0, lib MIT) et requiert un **token client Mapillary gratuit** — voir §2.1. Sans ce token, les 4 autres modes fonctionnent normalement ; seul le mode street affiche un message d'indisponibilité.
## 1. Application SvelteKit
```bash
# Prérequis : Node.js >= 20 (via nodesource ou nvm)
git clone https://codeberg.org/OKI/jwe.git
cd jwe/app
npm ci
npm run build # produit app/build (adapter-node)
```
Lancer en production (port 3000 par défaut) :
```bash
PORT=3000 node build
```
Service systemd `/etc/systemd/system/jwe.service` :
```ini
[Unit]
Description=JWE — jeu de géolocalisation OKI
After=network.target
[Service]
Type=simple
User=jwe
WorkingDirectory=/srv/jwe/app
Environment=PORT=3000
Environment=ORIGIN=https://jwe.o-k-i.net
Environment=PUBLIC_TILES_URL=https://tiles.o-k-i.net/styles/oki/style.json
Environment=PUBLIC_MAPILLARY_TOKEN=MLY|xxxxxxxx|xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
ExecStart=/usr/bin/node build
Restart=on-failure
[Install]
WantedBy=multi-user.target
```
## 2.1 Token Mapillary (mode street « An lari a »)
1. Créez un compte sur [mapillary.com](https://www.mapillary.com) puis une application sur le [dashboard développeurs](https://www.mapillary.com/dashboard/developers) : récupérez le **client token** (format `MLY|…|…`).
2. Exposez-le via `PUBLIC_MAPILLARY_TOKEN` (service systemd ci-dessus, ou `app/.env` en développement — voir `app/.env.example`). C'est un **token client** : conçu pour être visible côté navigateur, rate-limité par application — ce n'est pas un secret.
3. Vérifiez périodiquement le corpus street (images parfois retirées par leurs auteurs) :
```bash
cd app && node scripts/validate-street.mjs # lit le token depuis .env
```
## 2. Reverse proxy (exemple nginx)
```nginx
server {
server_name jwe.o-k-i.net;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# + TLS via certbot
```
## 3. Tiles cartographiques auto-hébergées (tileserver-gl)
Par défaut l'application utilise OpenFreeMap (libre, sans clé). Pour une souveraineté complète, hébergez vos propres tiles OSM des 4 régions.
### 3.1 Récupérer les extraits OpenStreetMap
```bash
mkdir -p /srv/tiles && cd /srv/tiles
# Guadeloupe, Martinique, Guyane : extraits Geofabrik
wget https://download.geofabrik.de/north-america/guadeloupe-latest.osm.pbf
wget https://download.geofabrik.de/north-america/martinique-latest.osm.pbf
wget https://download.geofabrik.de/south-america/french-guiana-latest.osm.pbf
# La Réunion
wget https://download.geofabrik.de/africa/reunion-latest.osm.pbf
```
### 3.2 Générer les .mbtiles
Avec [openmaptiles](https://github.com/openmaptiles/openmaptiles) (Docker requis) : générez un `.mbtiles` par région puis fusionnez-les avec `tile-join` (paquet `tippecanoe`) :
```bash
tile-join -o dom-tom.mbtiles guadeloupe.mbtiles martinique.mbtiles guyane.mbtiles reunion.mbtiles
```
(Alternative plus légère : extraire les 4 régions d'un `.mbtiles` Monde basse-résolution `tile-join --bbox=…` par région, puisque la carte de devinette n'a pas besoin d'un zoom très fin partout.)
### 3.3 Servir avec tileserver-gl
```bash
docker run --rm -d --name tiles -v /srv/tiles:/data -p 8080:8080 \
maptiler/tileserver-gl dom-tom.mbtiles
```
Copiez le style OKI de l'application (`app/src/lib/map/style-oki.json`) dans `/srv/tiles/styles/oki/`, adaptez son URL de source vers votre `dom-tom.mbtiles`, puis :
```bash
Environment=PUBLIC_TILES_URL=https://tiles.o-k-i.net/styles/oki/style.json
```
### 3.4 Fontes et sprites
tileserver-gl sert aussi les fontes (glyphs) et sprites référencés par le style. Les fontes open-source utilisées par le style OKI (ex. Noto Sans) se récupèrent via `openmaptiles/fonts` ou `klokantech/tileserver-gl-fonts`.
## 4. Cache Wikipedia
Le endpoint `/api/wiki/[qid]` met en cache les extraits 24 h en mémoire. Aucune configuration requise ; pour un cache partagé entre instances, placez nginx en cache proxy devant `/api/wiki/` (respecte déjà `Cache-Control`).
## 5. Mise à jour
```bash
cd jwe && git pull && cd app && npm ci && npm run build
systemctl restart jwe
```
L'ajout de lieux (voir `docs/contribution.md`) ne demande qu'un rebuild + restart : le corpus est embarqué dans le build.
-9
View File
@@ -1,9 +0,0 @@
<?= "
<div style='display: flex; justify-content: center; align-items: center;'>
<h1 id='title'>$zone</h1>
<a style='text-decoration: none;' href='/'>
<button id='back-button'>🔙 Retour</button>
</a>
</div>
";
?>
-12
View File
@@ -1,12 +0,0 @@
<?= "
<div style='display: flex; justify-content: center;'>
<button class='game-button' disabled style='margin-right: 2em;' onClick='startGame()' id='start' type='button'>Commencer la partie</button>
<button class='game-button' disabled onClick='restartGame()' id='restart' type='button'>Recommencer</button>
</div>
<div id='chrono'></div>
<div id='score' style='display: flex; justify-content: center;'></div>
<div id='question'></div>
";
?>
-19
View File
@@ -1,19 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Choisis une carte</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="./css/index.css" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
</head>
<body>
<h1>Choisis une carte</h1>
<ul>
<li><a href="kat/DINA-MORGABIN.php">DINA MORGABIN (La Réunion)</a></li>
<li><a href="kat/GUYANE.php">GUYANE</a></li>
<li><a href="kat/KMT.php">KMT (Afrique)</a></li>
<li><a href="kat/KARUKERA.php">KARUKERA (Guadeloupe)</a></li>
<li><a href="kat/WANAKAERA.php">WANAKAERA (Martinique)</a></li>
</ul>
</body>
</html>
-554
View File
@@ -1,554 +0,0 @@
/**
* js/map.js
*/
/**
* Typos
*
* Après l'ajout de l'Afrique, on remplace "communes" par "zones"
* Zones = Communes ou Pays
*/
/**
* Récupérer le nom du fichier actuel (ex: 971.php) et en extraire le code du département (ex: 971).
*/
const currentFileName = window.location.pathname.split('/').pop()
const codeCarte = currentFileName.split('.')[0]
const startButton = document.getElementById('start')
const restartButton = document.getElementById('restart')
restartButton.setAttribute('disabled', true)
/**
* Définir le centre , le niveau de zoom et le style de la carte en fonction du code du département.
*/
let centerCoordinates
let zoomLevel
let styleFileName
switch (codeCarte) {
case 'KMT':
centerCoordinates = [21.21, 1.36] // Afrique
zoomLevel = 2.7
styleFileName = 'ortho-jwe-KMT.json'
break
case 'KARUKERA':
centerCoordinates = [-61.4167, 16.25] // Guadeloupe
zoomLevel = 9
styleFileName = 'ortho.json'
break
case 'WANAKAERA':
centerCoordinates = [-61.01635, 14.60285] // Martinique
zoomLevel = 9.5
styleFileName = 'ortho.json'
break
case 'GUYANE':
centerCoordinates = [-53.1258, 3.9339] // Guyane française
zoomLevel = 7
styleFileName = 'ortho-jwe.json'
break
case 'DINA-MORGABIN':
centerCoordinates = [55.52905, -21.13014] // La Réunion
styleFileName = 'ortho.json'
zoomLevel = 9.5
break
default:
centerCoordinates = [-61.4167, 16.25] // Par défaut (Guadeloupe)
styleFileName = 'ortho.json'
zoomLevel = 9.5
}
/**
* Définit les décalages des popups en fonction de leur position.
*/
const popupOffsets = {
'top': [0, 0],
'top-left': [0, 0],
'top-right': [0, 0],
'bottom': [0, -30],
'bottom-left': [0, -50],
'bottom-right': [0, -50],
'left': [25, -25],
'right': [-25, -25]
}
/**
* Référence aux éléments HTML pour afficher le score.
*/
let ok
let ko
let penaltyElement
/**
* Gestion du temps écoulé
*/
let gameTime = 0
let gameMinute = 0
let gameSecond = 0
let gamePenalty = 0
let gameTimeWithPenalty = 0
let gameMinuteWithPenalty = 0
let gameSecondWithPenalty = 0
let intervalId
/**
* État actuel de la commune survolée.
*/
let hoveredStateId = null
/**
* Référence à la commune actuellement sélectionnée pour trouver.
*/
let currentZone = null
/**
* Ensemble des codes des communes déjà trouvées correctement.
*/
const correctAnswers = new Set()
/**
* Permet de remettre le jeu à 0
*/
function resetGame() {
ok.innerText = 0
ko.innerText = 0
correctAnswers.clear()
clearInterval(intervalId)
intervalId = null
gameTime = 0
gamePenalty = 0
gameTimeWithPenalty = 0
}
/**
* Active le bouton "Commencer la partie" au chargement de la page
*/
window.onload = function() {
const startElement = document.getElementById('start')
startElement.removeAttribute('disabled')
}
function startGame() {
loadMap()
const question = document.getElementById('question')
const score = document.getElementById('score')
const chrono = document.getElementById('chrono')
question.innerHTML = `<p style='font-weight: bold;'>Trouve ${codeCarte === 'KMT' ? 'le pays' : 'la commune'}</p><p id='commune' style='font-size: 30px; font-weight: bold; color: #1F51FF'>...</p>`
score.innerHTML = "<p style='color: green; font-weight: bold; margin-right: 2em;'>Correct ✅ : <span style='color: black;' id='OK'>0</span></p><p style='color: red; font-weight: bold;'>Faux ❌ : <span style='color: black;' id='KO'>0</span></p>"
chrono.innerHTML = "<p>Temps écoulé : <span id='time'></span><span style='margin-left: 1em;color: red; font-weight: bold;' id='penalty'></span></p>"
communeObserver()
ok = document.getElementById('OK')
ko = document.getElementById('KO')
penaltyElement = document.getElementById('penalty')
startButton.setAttribute('disabled', true)
restartButton.removeAttribute('disabled')
resetGame()
}
/**
* Recommencer la partie
*/
function restartGame() {
startGame()
}
/**
* Observe le contenu de l'élément ayant pour id "commune"
*/
function communeObserver(){
const communeElement = document.getElementById('commune')
const timeElement = document.getElementById('time')
// Options de l'observateur (quelles sont les mutations à observer)
const config = { childList: true, subtree: true, characterData: true }
// Fonction callback à éxécuter quand une mutation est observée
const callback = function (mutationsList) {
for (var mutation of mutationsList) {
if (mutation.type == "childList" || mutation.type == "characterData") {
// Vérifie si le contenu de la balise span n'est pas égal à "..."
if (communeElement.textContent.trim() !== "...") {
// Vérifie si setInterval n'est pas déjà en cours
if (!intervalId) {
intervalId = setInterval(() => {
gameTime++
gameTimeWithPenalty = gameTime + gamePenalty
if (gameTimeWithPenalty >= 60) {
gameMinuteWithPenalty = String(gameTimeWithPenalty / 60).split('.')[0]
gameMinute = String(gameTime / 60).split('.')[0]
gameSecondWithPenalty = gameTimeWithPenalty % 60
gameSecond = gameTime % 60
timeElement.innerText = `${gameMinuteWithPenalty} minute${gameMinuteWithPenalty > 1 ? 's' : ''} ${gameSecondWithPenalty} seconde${gameSecondWithPenalty > 1 ? 's' : ''}`
} else {
timeElement.innerText = `${gameTimeWithPenalty} seconde${gameTimeWithPenalty > 1 ? 's' : ''}`
}
}, 1000)
}
}
}
}
}
// Créé une instance de l'observateur lié à la fonction de callback
const observer = new MutationObserver(callback)
// Commence à observer le noeud cible pour les mutations précédemment configurées
observer.observe(communeElement, config)
}
/**
* Récupère les propriétés des communes depuis un fichier GeoJSON en fonction du code du département.
*
* @async
* @param {string} codeCarte - Code de la carte.
* @returns {Promise<Object[]>} Promesse résolue avec les propriétés des communes.
*/
async function getFile(codeCarte) {
try {
const response = await fetch(`../kat/data/${codeCarte}/contours-${codeCarte === 'KMT' ? 'pays' : 'communes'}.geojson`)
if (!response.ok) {
throw new Error(`Échec du chargement du fichier JSON : ${response.statusText}`)
}
data = await response.json()
return data.features.map(({properties}) => properties)
} catch (error) {
console.error('Erreur:', error)
throw new Error(error)
}
}
/**
* Récupère les coordonnées du centre de la commune depuis le fichier "centres.json" en fonction du code du département.
*
* @param {string} codeCarte - Code de la carte.
* @param {string} codeZone - Code de la zone.
* @returns {Promise<number[]>} Promesse résolue avec les coordonnées du centre de la commune.
*/
async function getZoneCenterCoordinates(codeCarte, codeZone) {
try {
// Utiliser fetch pour lire le fichier "centres.json"
const response = await fetch(`../kat/data/${codeCarte}/centres.json`)
if (!response.ok) {
throw new Error(`Échec du chargement du fichier JSON : ${response.statusText}`)
}
const centerData = await response.json()
// Vérifier si le code de la zone existe dans les données
if (codeZone in centerData) {
const coordinates = centerData[codeZone]
return coordinates
} else {
throw new Error(`Aucune donnée de centre trouvée pour la commune : ${codeZone}`)
}
} catch (error) {
console.error('Erreur lors de la récupération des coordonnées du centre de la commune :', error)
throw new Error(error)
}
}
/**
* Met à jour le score en fonction de la réponse.
*
* @param {boolean} isCorrect - Indique si la réponse est correcte.
*/
function updateScore(isCorrect) {
if (isCorrect) {
ok.innerText = Number.parseInt(ok.innerText, 10) + 1
} else {
ko.innerText = Number.parseInt(ko.innerText, 10) + 1
gamePenalty += 5
penaltyElement.style.opacity = 1
penaltyElement.innerText = '+ 5 secondes'
setTimeout(() => {
penaltyElement.style.opacity = 0
penaltyElement.innerText = ''
}, 2000)
}
}
/**
* Sélectionne une commune au hasard parmi celles qui n'ont pas encore été trouvées.
*
* @param {Array} zones - Liste de toutes les zones.
* @returns {Object|null} Retourne la commune sélectionnée ou null si toutes les zones ont été trouvées.
*/
function pickRandomZone(zones) {
const zonesRestantes = zones.filter(commune => !correctAnswers.has(commune.code))
if (zonesRestantes.length === 0) {
return null
}
const index = Math.floor(Math.random() * zonesRestantes.length)
return zonesRestantes[index]
}
/**
* Vérifie si le code de la zone cliquée correspond à la commune actuelle à trouver.
*
* @param {string} codeZone - code de la zone à vérifier.
* @returns {boolean} Résultat de la vérification.
*/
function checkAnswer(codeZone) {
return currentZone && codeZone === currentZone.code
}
/**
* Charge la carte
*/
function loadMap() {
/**
* Initialise et configure la carte
*/
const map = new maplibregl.Map({
container: 'map',
style: `../kat/styles/${styleFileName}`,
center: centerCoordinates,
zoom: zoomLevel
})
if (codeCarte !== 'GUYANE') {
/**
* Désactive le zoom, le double-clic, le déplacement de la carte pour les cartes autres que celle la Guyane.
*/
map.scrollZoom.disable()
map.doubleClickZoom.disable()
map.dragPan.disable()
} else {
/**
* Ajoute les contrôles de navigation à la carte, et définit les niveaux de zoom minimum et maximum pour la Guyane.
*/
map.addControl(new maplibregl.NavigationControl({showCompass: false}))
map.setMinZoom(7)
map.setMaxZoom(9.5)
}
if (codeCarte === 'KMT') {
/**
* Ajoute les contrôles de navigation à la carte, et définit les niveaux de zoom minimum et maximum pour l'Afrique'.
*/
map.addControl(new maplibregl.NavigationControl({showCompass: false}))
map.setMinZoom(2.4)
map.setMaxZoom(9)
map.dragPan.enable()
}
/**
* Code pour la gestion des événements de la carte (load, mousemove, mouseleave, click).
*/
map.on('load', async () => {
const zones = await getFile(codeCarte)
/**
* Définit la zone actuelle à trouver et met à jour l'affichage.
*
* @param {Object} zone - La zone à définir comme actuelle.
*/
function setZone(zone) {
if (currentZone) {
map.setFeatureState(
{source: 'communes', id: currentZone.code},
{current: false}
)
}
currentZone = zone
document.getElementById('commune').innerText = zone.nom
map.setFeatureState(
{source: 'communes', id: zone.code},
{current: true}
)
}
/**
* Ajouter une source de données pour les communes.
*/
map.addSource('communes', {
'type': 'geojson',
'data': `../kat/data/${codeCarte}/contours-${codeCarte === 'KMT' ? 'pays' : 'communes'}.geojson`,
'promoteId': 'code'
})
/**
* Ajouter une couche de remplissage pour les communes.
*/
map.addLayer({
'id': 'drom',
'type': 'fill',
'source': 'communes',
'layout': {},
'paint': {
'fill-color': '#1F51FF',
'fill-opacity': [
'case',
['boolean', ['feature-state', 'hover'], false],
0.8,
0
]
}
})
/**
* Ajouter une couche de remplissage pour les communes (2ème couche), en prenant en compte les réponses correctes et incorrectes.
*/
map.addLayer({
'id': 'drom-2',
'type': 'fill',
'source': 'communes',
'layout': {},
'paint': {
'fill-color': [
'case',
['boolean', ['feature-state', 'correct'], false], '#00FF00',
['boolean', ['feature-state', 'incorrect'], false], '#FF0000',
'rgba(0,0,0,0)'
],
'fill-opacity': [
'case',
['boolean', ['feature-state', 'hover'], false], 0.5,
0.8
]
}
})
/**
* Gère l'evenement mousemove (quand la souris survole la commune)
*/
map.on('mousemove', 'drom', e => {
map.getCanvas().style.cursor = 'pointer'
if (e.features.length > 0) {
if (hoveredStateId) {
map.setFeatureState(
{source: 'communes', id: hoveredStateId},
{hover: false}
)
}
hoveredStateId = e.features[0].id
map.setFeatureState(
{source: 'communes', id: hoveredStateId},
{hover: true}
)
}
})
/**
* Gère l'evenement mouseleave (quand la souris quitte la zone)
*/
map.on('mouseleave', 'drom', () => {
map.getCanvas().style.cursor = ''
if (hoveredStateId) {
map.setFeatureState(
{source: 'communes', id: hoveredStateId},
{hover: false}
)
}
hoveredStateId = null
})
/**
* Gère l'evenement click (quand on clique sur la zone)
*/
map.on('click', 'drom', async e => {
if (e.features.length > 0) {
const clickedCodeZone = e.features[0].id
const clickedZoneNom = e.features[0].properties.nom
const isCorrect = checkAnswer(clickedCodeZone)
if (isCorrect) {
updateScore(true)
const centerCoordinates = await getZoneCenterCoordinates(codeCarte, clickedCodeZone)
const popup = new maplibregl.Popup({offset: popupOffsets, closeButton: false, className: 'popup-ok'})
.setLngLat([centerCoordinates[0], centerCoordinates[1]])
.setHTML(`<h3>Bravo, c'est ${clickedZoneNom}</h3>`)
.setMaxWidth('200px')
.addTo(map)
setTimeout(() => {
popup.remove()
}, 1500)
correctAnswers.add(clickedCodeZone)
zones.forEach(commune => {
map.setFeatureState(
{source: 'communes', id: commune.code},
{incorrect: false}
)
})
map.setFeatureState(
{source: 'communes', id: clickedCodeZone},
{correct: true, current: false}
)
const newZone = pickRandomZone(zones)
if (newZone) {
setZone(newZone)
} else {
const totalAnswers = Number.parseInt(ok.innerText, 10) + Number.parseInt(ko.innerText, 10)
const percentageCorrectAnswers = (Number.parseInt(ok.innerText, 10) / totalAnswers) * 100
let elapsedTime = `${gameTime} seconde${gameTime > 1 ? 's' : ''}`
let elapsedTimeWithPenalty = `${gameTimeWithPenalty} seconde${gameTimeWithPenalty > 1 ? 's' : ''}`
if (gameTime >= 60) {
elapsedTime = `${gameMinute} minute${gameMinute > 1 ? 's' : ''} ${gameSecond} seconde${gameSecond > 1 ? 's' : ''}`
}
if (gameTimeWithPenalty >= 60) {
elapsedTimeWithPenalty = `${gameMinuteWithPenalty} minute${gameMinuteWithPenalty > 1 ? 's' : ''} ${gameSecondWithPenalty} seconde${gameSecondWithPenalty > 1 ? 's' : ''}`
}
alert(`${Math.round(percentageCorrectAnswers)}% de bonnes réponses !
\nTemps écoulé : ${elapsedTime} ! ${gamePenalty ? `
\nPénalité : ${gamePenalty} secondes` : '\nAucune pénalité !'}
\nTemps total : ${elapsedTimeWithPenalty}`)
clearInterval(intervalId)
gameTime = 0
gameTimeWithPenalty = 0
setTimeout(() => {
location.reload()
}, 1000)
}
} else {
updateScore(false)
const centerCoordinates = await getZoneCenterCoordinates(codeCarte, clickedCodeZone)
const popup = new maplibregl.Popup({offset: popupOffsets, closeButton: false, className: 'popup-ko'})
.setLngLat([centerCoordinates[0], centerCoordinates[1]])
.setHTML(`<h3>Faux, c'est ${clickedZoneNom}</h3>`)
.setMaxWidth('200px')
.addTo(map)
setTimeout(() => {
popup.remove()
}, 1500)
map.setFeatureState(
{source: 'communes', id: clickedCodeZone},
{incorrect: true}
)
}
}
})
const zone = pickRandomZone(zones)
setZone(zone)
})
}
-20
View File
@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>JWE - KAT</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.css" />
<link rel="stylesheet" href="../css/map.css" />
</head>
<body>
<?php
$zone = 'DINA MORGABIN (La Réunion)';
include('../game-control/back.php');
include('../game-control/start.php');
?>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.js"></script>
<script src="../js/map.js"></script>
</body>
</html>
-20
View File
@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>JWE - KAT</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.css" />
<link rel="stylesheet" href="../css/map.css" />
</head>
<body>
<?php
$zone = 'GUYANE';
include('../game-control/back.php');
include('../game-control/start.php');
?>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.js"></script>
<script src="../js/map.js"></script>
</body>
</html>
-20
View File
@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>JWE - KAT</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.css" />
<link rel="stylesheet" href="../css/map.css" />
</head>
<body>
<?php
$zone = 'KARUKERA (Guadeloupe)';
include('../game-control/back.php');
include('../game-control/start.php');
?>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.js"></script>
<script src="../js/map.js"></script>
</body>
</html>
-20
View File
@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>JWE - KAT</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.css" />
<link rel="stylesheet" href="../css/map.css" />
</head>
<body>
<?php
$zone = 'KMT (Afrique)';
include('../game-control/back.php');
include('../game-control/start.php');
?>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.js"></script>
<script src="../js/map.js"></script>
</body>
</html>
-20
View File
@@ -1,20 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>JWE - KAT</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.css" />
<link rel="stylesheet" href="../css/map.css" />
</head>
<body>
<?php
$zone = 'WANAKAERA (Martinique)';
include('../game-control/back.php');
include('../game-control/start.php');
?>
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/maplibre-gl/5.0.0/maplibre-gl.js"></script>
<script src="../js/map.js"></script>
</body>
</html>
-1
View File
@@ -1 +0,0 @@
{"97401":[55.3629,-21.2019],"97402":[55.6266,-21.0316],"97403":[55.4937,-21.2108],"97404":[55.358,-21.2348],"97405":[55.5706,-21.333],"97406":[55.6442,-21.153],"97407":[55.3038,-20.946],"97408":[55.3918,-20.9967],"97409":[55.6373,-20.9568],"97410":[55.6312,-21.0887],"97411":[55.4444,-20.9434],"97412":[55.644,-21.2921],"97413":[55.3432,-21.1816],"97414":[55.4224,-21.2255],"97415":[55.3402,-21.0366],"97416":[55.5043,-21.309],"97417":[55.7436,-21.3084],"97418":[55.5234,-20.9463],"97419":[55.7418,-21.1778],"97420":[55.5936,-20.9507],"97421":[55.5145,-21.0524],"97422":[55.5701,-21.225],"97423":[55.3377,-21.1138],"97424":[55.4555,-21.1403]}
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
{"97301":[-52.4797,4.0081],"97302":[-52.3319,4.9464],"97303":[-53.2979,5.2395],"97304":[-52.7764,4.9085],"97305":[-52.4834,4.9925],"97306":[-53.6784,4.9955],"97307":[-52.3498,4.8281],"97308":[-52.075,3.8078],"97309":[-52.2809,4.8897],"97310":[-52.5164,4.4685],"97311":[-54.0105,4.9478],"97312":[-53.0097,5.2418],"97313":[-52.5059,4.8124],"97314":[-51.8261,4.2104],"97352":[-53.4333,3.8181],"97353":[-53.8275,3.049],"97356":[-52.6916,2.8679],"97357":[-54.1148,4.3756],"97358":[-53.1108,4.4853],"97360":[-54.2171,4.9019],"97361":[-53.9167,5.6743],"97362":[-54.0463,4.0165]}
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
{"ETH":[38.947611801806495,9.176814264950167],"SDS":[30.333984675480757,7.914722205528841],"SOM":[46.5464912522007,6.019175354863551],"KEN":[37.67592532581279,0.5754517148962938],"MWI":[34.09609576769113,-12.735921358471073],"TZA":[35.02498976184473,-6.566525957661288],"SOL":[45.53479066506411,10.023473808092941],"MAR":[-9.046877128746582,28.467636665531234],"SAH":[-12.391359135142558,24.416734554893036],"COG":[14.38464128008542,-1.1354128251164652],"COD":[23.704062532123782,-4.540787787186473],"NAM":[18.118996644631416,-21.83831839276176],"ZAF":[25.24975775021357,-28.817139228003967],"LBY":[17.664886093139636,28.172444725036605],"TUN":[9.882258580942635,34.22426090761612],"ZMB":[28.80207441614033,-12.512532465508636],"SLE":[-11.936779785156242,8.548585165700597],"GIN":[-10.715817638913904,10.109710183267284],"LBR":[-9.0900040336277,6.986474255548001],"CAF":[20.072171294504646,6.3873503410410155],"SDN":[30.120938288256728,13.975380990751114],"DJI":[42.62365767045457,11.756886541193175],"ERI":[39.367317191633596,15.18048657614088],"CIV":[-5.781225753157097,7.972692202215326],"MLI":[-5.421274816662242,14.822845678349621],"SEN":[-14.389369189049583,14.030028086260339],"NGA":[7.736925662551809,8.550665249482046],"BEN":[2.3506708850599414,9.720748943172085],"AGO":[17.418358503069197,-10.850000871930797],"BWA":[24.581611328124996,-22.54493652343752],"ZWE":[29.6308403060281,-19.12852949334319],"TCD":[18.96083041487069,12.76727387526939],"DZA":[1.7720829050164644,29.20973285875821],"MOZ":[35.32805940685356,-17.11878541610783],"SWZ":[31.558316617398656,-26.473094383445954],"BDI":[29.989004159902603,-3.062598924512992],"RWA":[29.916395531631114,-2.013365806021347],"UGA":[32.11797202339386,1.3982593728177313],"LSO":[28.192589689555945,-29.671546052631577],"CMR":[13.006806556679795,6.257060071185528],"GAB":[11.616017795138896,-0.8739639395254695],"NER":[6.34184839443898,15.351725132258853],"BFA":[-1.6133907257564375,11.978387935577883],"TGO":[0.7269224654796614,8.681028948643402],"GHA":[-1.0836453419811212,8.284749272184547],"GNB":[-15.375719884923969,11.688141034100504],"EGY":[30.779661923363108,27.661831325954854],"MRT":[-11.604420093309178,19.791261755485873],"GNQ":[9.71551682692309,2.0668689903846107],"GMB":[-15.49098985460068,13.434295654296868],"MDG":[46.962987167300405,-17.773911299904935],"COM":[43.85425415039061,-11.994052124023446],"STP":[6.957070312500013,0.8602416992187436],"CPV":[-23.908437994462016,16.04201691060126]}
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
{"97101":[-61.4967,16.2678],"97102":[-61.4698,16.4668],"97103":[-61.5951,16.2498],"97104":[-61.7158,16.0497],"97105":[-61.7294,15.9992],"97106":[-61.7578,16.1387],"97107":[-61.6197,16.0486],"97108":[-61.2296,15.9176],"97109":[-61.689,16.0057],"97110":[-61.0814,16.2972],"97111":[-61.7831,16.3194],"97112":[-61.2929,15.9085],"97113":[-61.4749,16.2274],"97114":[-61.615,16.1231],"97115":[-61.6695,16.2443],"97116":[-61.4988,16.3212],"97117":[-61.36,16.3354],"97118":[-61.658,16.1695],"97119":[-61.4547,16.3921],"97120":[-61.5379,16.2351],"97121":[-61.7651,16.227],"97122":[-61.488,16.4201],"97124":[-61.6953,16.0406],"97125":[-61.2539,16.2784],"97126":[-61.2732,15.9654],"97128":[-61.3896,16.2565],"97129":[-61.6836,16.2937],"97130":[-61.6326,15.8554],"97131":[-61.5892,15.8579],"97132":[-61.6493,15.9931],"97133":[-61.6929,15.9607],"97134":[-61.717,16.0847]}
File diff suppressed because one or more lines are too long
-1
View File
@@ -1 +0,0 @@
{"97201":[-61.1305,14.816],"97202":[-61.0736,14.4996],"97203":[-61.1237,14.841],"97204":[-61.1584,14.7041],"97205":[-61.1297,14.6593],"97206":[-61.0165,14.4787],"97207":[-60.9685,14.5785],"97208":[-61.1207,14.7228],"97209":[-61.0686,14.6492],"97210":[-60.8976,14.6093],"97211":[-61.1837,14.847],"97212":[-61.0303,14.7084],"97213":[-60.9923,14.6231],"97214":[-61.074,14.7995],"97215":[-61.1465,14.8474],"97216":[-61.0531,14.7796],"97217":[-60.8589,14.4822],"97218":[-61.1217,14.7695],"97219":[-61.1963,14.822],"97220":[-60.897,14.5027],"97221":[-60.9623,14.5262],"97222":[-60.9383,14.675],"97223":[-60.9233,14.5618],"97224":[-61.0407,14.6835],"97225":[-61.1736,14.7717],"97226":[-60.8516,14.4314],"97227":[-60.9467,14.4904],"97228":[-61.0084,14.773],"97229":[-61.1001,14.6518],"97230":[-60.9469,14.7381],"97231":[-61.0376,14.5329],"97232":[-60.8594,14.5421],"97233":[-61.1362,14.7046],"97234":[-61.1459,14.6747]}
File diff suppressed because one or more lines are too long
-56
View File
@@ -1,56 +0,0 @@
{
"version": 8,
"glyphs":"https://wxs.ign.fr/static/vectorTiles/fonts/{fontstack}/{range}.pbf",
"sources": {
"raster-tiles": {
"type": "raster",
"tiles": [
"https://wxs.ign.fr/essentiels/geoportail/wmts?layer=ORTHOIMAGERY.ORTHOPHOTOS&style=normal&tilematrixset=PM&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fjpeg&TileMatrix={z}&TileCol={x}&TileRow={y}"
],
"tileSize": 256,
"attribution": "<a target='_blank' href='https://geoservices.ign.fr/documentation/donnees/ortho/bdortho'>© IGN</a>"
},
"KMT": {
"type": "vector",
"url": "https://tiles.jwe.ovh/data/KMT.json"
}
},
"layers": [
{
"id": "simple-tiles",
"type": "raster",
"source": "raster-tiles"
},
{
"id": "boundary",
"type": "line",
"source": "KMT",
"source-layer": "boundary",
"minzoom": 2,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "#ffffff",
"line-width": {
"base": 1.4,
"stops": [
[
4,
2
],
[
5,
1
],
[
12,
3
]
]
}
}
}
]
}
-142
View File
@@ -1,142 +0,0 @@
{
"version": 8,
"glyphs":"https://wxs.ign.fr/static/vectorTiles/fonts/{fontstack}/{range}.pbf",
"sources": {
"raster-tiles": {
"type": "raster",
"tiles": [
"https://wxs.ign.fr/essentiels/geoportail/wmts?layer=ORTHOIMAGERY.ORTHOPHOTOS&style=normal&tilematrixset=PM&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image%2Fjpeg&TileMatrix={z}&TileCol={x}&TileRow={y}"
],
"tileSize": 256,
"attribution": "<a target='_blank' href='https://geoservices.ign.fr/documentation/donnees/ortho/bdortho'>© IGN</a>"
},
"cadastre": {
"type": "vector",
"url": "https://openmaptiles.geo.data.gouv.fr/data/cadastre.json"
},
"decoupage-administratif": {
"type": "vector",
"url": "https://openmaptiles.geo.data.gouv.fr/data/decoupage-administratif.json"
}
},
"layers": [
{
"id": "simple-tiles",
"type": "raster",
"source": "raster-tiles"
},
{
"id": "communes",
"type": "line",
"source": "decoupage-administratif",
"source-layer": "communes",
"minzoom": 2,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "#ffffff",
"line-width": {
"base": 1.4,
"stops": [
[
4,
0.4
],
[
5,
1
],
[
12,
3
]
]
}
}
},
{
"id": "departements",
"type": "line",
"source": "decoupage-administratif",
"source-layer": "departements",
"maxzoom":9,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "hsl(248, 7%, 66%)",
"line-dasharray": [
3,
1,
1,
1
],
"line-width": {
"base": 1.4,
"stops": [
[
0,
0.6
],
[
4,
1.4
],
[
5,
2
],
[
12,
8
]
]
}
}
},
{
"id": "regions",
"type": "line",
"source": "decoupage-administratif",
"source-layer": "regions",
"maxzoom":5,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "hsl(248, 7%, 70%)",
"line-dasharray": [
3,
1,
1,
1
],
"line-width": {
"base": 1.6,
"stops": [
[
0,
0.6
],
[
4,
1.4
],
[
5,
2
],
[
12,
8
]
]
}
}
}
]
}
-142
View File
@@ -1,142 +0,0 @@
{
"version": 8,
"glyphs":"https://orangemug.github.io/font-glyphs/glyphs/{fontstack}/{range}.pbf",
"sources": {
"raster-tiles": {
"type": "raster",
"tiles": [
"https://data.geopf.fr/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTHOIMAGERY.ORTHOPHOTOS&STYLE=normal&FORMAT=image/jpeg&TILEMATRIXSET=PM&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}"
],
"tileSize": 256,
"attribution": "<a target='_blank' href='https://geoservices.ign.fr/documentation/donnees/ortho/bdortho'>© IGN</a>"
},
"cadastre": {
"type": "vector",
"url": "https://openmaptiles.geo.data.gouv.fr/data/cadastre.json"
},
"decoupage-administratif": {
"type": "vector",
"url": "https://openmaptiles.geo.data.gouv.fr/data/decoupage-administratif.json"
}
},
"layers": [
{
"id": "simple-tiles",
"type": "raster",
"source": "raster-tiles"
},
{
"id": "communes",
"type": "line",
"source": "decoupage-administratif",
"source-layer": "communes",
"minzoom": 2,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "#ffffff",
"line-width": {
"base": 1.4,
"stops": [
[
4,
0.4
],
[
5,
1
],
[
12,
3
]
]
}
}
},
{
"id": "departements",
"type": "line",
"source": "decoupage-administratif",
"source-layer": "departements",
"maxzoom":9,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "hsl(248, 7%, 66%)",
"line-dasharray": [
3,
1,
1,
1
],
"line-width": {
"base": 1.4,
"stops": [
[
0,
0.6
],
[
4,
1.4
],
[
5,
2
],
[
12,
8
]
]
}
}
},
{
"id": "regions",
"type": "line",
"source": "decoupage-administratif",
"source-layer": "regions",
"maxzoom":5,
"layout": {
"line-join": "round",
"visibility": "visible"
},
"paint": {
"line-color": "hsl(248, 7%, 70%)",
"line-dasharray": [
3,
1,
1,
1
],
"line-width": {
"base": 1.6,
"stops": [
[
0,
0.6
],
[
4,
1.4
],
[
5,
2
],
[
12,
8
]
]
}
}
}
]
}
+254
View File
@@ -0,0 +1,254 @@
Voici le prompt mis à jour. Les hésitations sur les librairies et les panoramas sont supprimées, et la dimension éducative/Wikipedia est intégrée comme un mécanisme de jeu à part entière (et non plus comme un simple fallback).
---
```
# Mission : JWE — Jeu de géolocalisation souverain type GeoGuessr
## Refonte complète · Svelte + Strapi/SvelteKit · MapLibre · Photos uniques · Éducation Wikipedia
---
## 1. Contexte et ambition
### 1.1 Projet source
- **URL actuelle** : https://labola.o-k-i.net/ORGANISATION-KA-INTERNATIONALE/JWE
- **Objet** : refonte complète pour en faire un jeu de géolocalisation dans l'esprit de GeoGuessr, centré sur 4 régions : **Guadeloupe, Martinique, Guyane, La Réunion**.
### 1.2 Mécanique de jeu verrouillée
- **Pas de Street View, pas de panoramas, pas de 3D.**
- Le joueur voit une **photo unique** d'un lieu (monument, paysage, rue, lieu culturel).
- Il doit placer un marqueur sur une carte pour deviner **la commune** (et par déduction la région).
- Le score est calculé selon la distance entre le marqueur et les coordonnées réelles.
- Après le score : phase éducative basée sur **Wikipedia/Wikidata** (voir §1.3).
### 1.3 Le pivot éducatif : Wikipedia/Wikidata comme cœur du jeu
JWE n'est pas qu'un jeu de score, c'est un outil de **souveraineté documentaire**.
- Si le lieu photographié possède une page Wikipedia : afficher un extrait de l'article, ses coordonnées Wikidata, et un lien "Lire plus sur Wikipédia".
- **Si le lieu n'a PAS de page Wikipedia ou de données Wikidata** : c'est intentionnel et pédagogique. Le jeu doit afficher un écran spécifique expliquant :
1. Pourquoi ce lieu n'est pas sur Wikipedia (lacune documentaire).
2. Pourquoi il est vital que les populations locales documentent leurs propres territoires (représentation numérique, décolonisation du savoir, importance pour les modèles d'IA qui s'entraînent sur ces données, tourisme, transmission).
3. Un appel à l'action : "Contribuer sur Wikipédia" avec un lien vers l'éditeur Wikipédia pré-rempli (ou des liens vers des tutos OKI/Wikimédiens locaux).
- **L'Agent Contenu doit intentionnellement inclure des lieux sans page Wikipedia** pour tester et démontrer cette fonctionnalité.
### 1.4 Cible OKI
- **Souverain** : zéro Google, zéro Mapbox. Carte MapLibre + tiles libres.
- **Éthique** : pas de loot boxes, pas de leaderboard forcé, pas d'anxiété.
- **Performant** : jouable sur téléphone en 4G caribéen.
- **Bilingue** : français / créole pour l'interface.
---
## 2. Stack technique (Verrouillée)
### 2.1 Front-end : Svelte 5 + SvelteKit 2
- Obligatoire. Compilateur léger, CSS scopé natif, SSR, MIT, PWA.
### 2.2 Cartographie : MapLibre GL JS (Verrouillé)
- **Obligatoire.** Pas d'évaluation de Cesium, iTowns ou Three.js à faire.
- MapLibre pour la carte de devinette (placement du marqueur) et la carte récapitulative.
- Style cartographique custom OKI (couleurs, fonts, labels) basé sur des tiles OpenStreetMap auto-hébergées ou libres.
- Zoom contraint aux 4 régions (le joueur ne peut pas scroller la carte en Europe ou aux US, ce qui donnerait un indice).
### 2.3 Back-end : Strapi ou SvelteKit seul (L'Architecte décide)
- **Critère** : qui ajoute les lieux ? Si contributeurs non-devs → Strapi. Si devs uniquement → SvelteKit avec fichiers JSON locaux.
- **Contrainte Wikipedia** : Ne **pas** stocker le texte Wikipedia en base. Le back-end (Strapi ou SvelteKit) doit interroger l'API Wikipedia/Wikidata en temps réel (ou avec un cache court) lors de l'affichage du résultat, à partir de l'ID Wikidata lié au lieu.
### 2.4 Base de données
- SQLite (frugalité OKI).
---
## 3. Design du jeu
### 3.1 Types de parties (Modes)
#### Mode 1 : « Konnèt moniman » (Reconnaître le monument)
- Photo d'un monument. Deviner la commune.
- Pas de limite de temps par défaut. Option timer activable.
- Indices progressifs optionnels (Région → Département → "C'est un fort colonial") avec pénalité de score.
#### Mode 2 : « Kote mwen ye ? » (Où suis-je ?)
- Photo d'un lieu ordinaire (rue, carrefour, bord de mer, forêt guyanaise).
- Deviner la commune. Timer optionnel.
#### Mode 3 : « Défi 5 rounds »
- 5 tours consécutifs mélangeant monuments et lieux.
- Résumé final avec la carte montrant les 5 marqueurs vs positions réelles.
#### Mode 4 : « Aprann » (Explorer)
- Pas de score. Parcourir la carte, cliquer sur les marqueurs, voir les photos et lire les fiches Wikipedia / les appels à contribution.
### 3.2 Système de score
#### Formule (adaptée à la taille des communes)
Les communes DOM sont petites. Un écart de 2 km peut signifier "à côté" ou "dans la commune d'à côté".
```
score = MAX_POINTS × e^(-distance / radius)
```
- `MAX_POINTS` = 5000.
- `radius` par difficulté :
- Facile : 50 km (tu peux te tromper de commune voisine)
- Moyen : 15 km (tu dois être dans la bonne commune)
- Difficile : 5 km (tu dois être dans le bon quartier)
- Expert : 1 km (précision rue)
#### Bonus / Pénalités
- Bonus temps (si activé) : max 20%.
- Pénalité indice : -10% par indice utilisé.
### 3.3 Schéma de données d'un lieu
```json
{
"id": "uuid",
"nom": "Fort Delgrès",
"nom_creole": "Fò Delgrès",
"region": "GUADELOUPE",
"commune": "Basse-Terre",
"coordonnees": { "lat": 16.0036, "lon": -61.7319 },
"categorie": "MONUMENT",
"difficulte": "MOYEN",
"wikidata_id": "Q2216838",
"photo": {
"url": "/assets/fort-delgres.webp",
"credit": "© Collectif OKI / Wikimedia Commons CC-BY-SA",
"alt": "Vue de face du Fort Delgrès en pierre grise surplombant la mer"
},
"indices": [
{ "niveau": 1, "texte": "Situé dans une capitale régionale" },
{ "niveau": 2, "texte": "C'est un fort historique face à la mer" }
]
}
```
*Note : Le texte éducatif vient de l'API Wikipedia via `wikidata_id`. Si `wikidata_id` est null, le front déclenche le mode "Lacune documentaire".*
---
## 4. Répartition des tâches par agent
### Agent Architecte (exécute en premier)
**Sorties attendues** :
1. **Décision Strapi vs SvelteKit seul** (argumentée).
2. **Architecture des tiles** : Source des tiles MapLibre (style OKI, auto-hébergé via tileserver-gl).
3. **Stratégie Wikipedia/Wikidata** : Comment le front/back récupère l'extrait Wikipedia en français à partir du `wikidata_id`. Endpoints API MWAPI à utiliser, stratégie de cache.
4. **Arborescence du projet** complète.
5. **Spécifications API REST** (sécurité anti-triche : ne jamais envoyer les coordonnées au client avant la soumission du marqueur).
### Agent Back-end (si Strapi retenu)
**Tâches** :
1. Strapi sur SQLite, zéro telemetry.
2. Content Type `Lieu` (schéma ci-dessus).
3. Endpoints custom sécurisés (random sans coordonnées, soumission guess).
4. Mise en place d'un proxy/cache léger pour les requêtes Wikipedia (pour ne pas se faire bloquer par l'API Wikimédia et accélérer l'affichage).
### Agent Front-end (SvelteKit) — Le cœur du projet
**Tâches** :
#### 4.1 Carte MapLibre
- Intégration de MapLibre GL JS.
- Style custom OKI (couleurs, typographie).
- Zoom contraint aux 4 régions (bounds géographiques stricts).
- Marqueur draggable pour la devinette.
- Boutons zoom +/- visibles (pas de geste obligatoire).
- Performance : lazy load de MapLibre (ne charger le JS que sur les écrans de jeu).
#### 4.2 L'Écran de jeu (Layout split)
- **Mobile** : Photo en haut (60%), Carte en bas (40%), Bouton "Valider" fixe en zone du pouce (tiers inférieur).
- **Desktop** : Photo à gauche (50%), Carte à droite (50%).
- Timer discret si activé (cercle qui se vide, couleurs douces).
- Bouton "Valider ma position" (action primaire unique, effet Von Restorff).
- Bouton "Passer" (secondaire).
- Bouton "Indice" (tertiaire, affiche le texte et la pénalité).
#### 4.3 L'Écran de résultat (CRUCIAL : Phase éducative)
Après validation, le marqueur vole vers la position réelle (sauf si `prefers-reduced-motion`).
**Cas A : Le lieu a un `wikidata_id` (Données existantes)**
- Afficher le score et la distance.
- Afficher un panneau éducatif contenant :
- Titre du lieu (lien vers la page Wikipedia).
- Extrait de l'article Wikipedia (récupéré via API).
- Commune et Région.
- Ton : "Tu as trouvé ! Apprends-en plus sur ce lieu."
**Cas B : Le lieu n'a PAS de `wikidata_id` (Lacune documentaire)**
- Afficher le score et la distance.
- Afficher un panneau **distinct visuellement** (couleur différente, iconographie spécifique) avec un message pédagogique fort :
- *Titre* : "Pwen blindé — Sa pa dokimanté" (Point aveugle — Ce n'est pas documenté).
- *Texte (FR)* : "Ce lieu existe, mais il n'a pas de page sur Wikipédia ni de fiche sur Wikidata. Pour nos régions, c'est un enjeu majeur : si nous ne documentons pas nos propres territoires, notre histoire et notre géographie disparaissent des cartes numériques et des bases de données mondiales (qui alimentent même l'intelligence artificielle)."
- *Texte (CRÉOLE)* : (Équivalent en créole, à intégrer via le système i18n).
- *Call to action* : Bouton "Kontribyé sou Wikipédia" (lien vers l'éditeur Wikipédia avec le titre du lieu pré-rempli dans la barre de recherche, ou lien vers un guide OKI "Comment contribuer à Wikipédia").
- **Soigner particulièrement cet écran (Peak-End rule de la doctrine OKI)** : c'est ici que le jeu devient un outil politique et éducatif, pas juste un divertissement.
#### 4.4 Écrans annexes
- **Accueil** : Titre "JWE", 4 cartes régions, choix du mode, bouton "Jouer" en zone pouce.
- **Résultat final** : Carte récapitulative, score total, bouton "Partager" (génère une image canvas à télécharger, pas de share API propriétaire).
- **Explorer** : Carte pleine page avec marqueurs, filtres par région, panneau latéral/bottom sheet avec la fiche Wikipedia ou le message de lacune.
#### 4.5 Technique
- PWA installable.
- Photos en WebP/AVIF, `srcset`, lazy loading.
- Navigation clavier sur la carte.
- i18n (FR / Créole) pour toute l'UI.
### Agent Contenu (exécute en parallèle)
**Tâches** :
1. Produire un **JSON de test de 40 lieux** (10/region).
2. **PIÈGE INTENTIONNEL** : Pour chaque région, inclure **2 à 3 lieux réels qui n'ont PAS de page Wikipedia française** (ex: une petite ravine en Guyane, un morne spécifique en Martinique, un calvaire ou une boutique historique en Guadeloupe, un site naturel à La Réunion). Laisser leur `wikidata_id` à `null` dans le JSON.
3. Pour les 7-8 autres lieux par région : fournir le vrai `wikidata_id` (ex: Q2216838 pour Fort Delgrès).
4. Fournir les URLs de photos Wikimedia Commons réelles (vérifier la licence CC).
### Agent Intégration & QA
**Tâches** :
1. Vérifier l'intégration MapLibre + API Lieux + API Wikipedia.
2. **Tester spécifiquement le Cas B (Lacune documentaire)** : vérifier que le message s'affiche correctement, que le ton est bon, que le lien de contribution fonctionne.
3. Jouer une partie complète.
4. **Checklist d'audit OKI** :
- [ ] Une seule action primaire par écran
- [ ] Mobile : bouton Valider en zone du pouce, carte utilisable au doigt
- [ ] Performance : premier écran < 3s, MapLibre lazy-loadé
- [ ] Éthique : pas de mécanique dopaminergique, score non punitif
- [ ] Éducation : les deux cas (Wiki OK / Wiki Manquant) fonctionnent et sont distincts visuellement
- [ ] Bilinguisme FR/créole présent (y compris dans le message de lacune)
- [ ] PWA installable
5. Mesures Core Web Vuts mobile 4G.
---
## 5. Doctrine UI/UX OKI (Extraits applicables)
- **Système 1** : L'écran de jeu est immédiatement lisible (Photo | Carte | Valider).
- **Von Restorff** : Le bouton "Valider" est le seul élément fortement coloré.
- **Peak-End** : L'écran de résultat (avec la fiche Wiki ou l'appel à contribution) doit laisser une impression forte et positive. C'est la fin du round, c'est ce dont le joueur se souviendra.
- **Calm technology** : Le timer est informatif, pas anxiogène.
- **Territoire** : Le créole est utilisé dans les micro-interactions ("Bravo !", "Kité sa ye ?", "Pwen blindé"). Les visuels de la carte ne sont pas le default bleu Google, mais un style OKI ancré dans le territoire.
---
## 6. Contraintes transversales
- **Licence** : MIT pour le code. Crédits obligatoires pour les photos Wikimedia.
- **Zéro dépendance propriétaire** : MapLibre (BSD), Svelte (MIT). Aucune clé API payante.
- **Sécurité** : Les coordonnées réelles ne sont jamais dans le payload initial envoyé au client.
- **Git** : Commits atomiques.
---
## 7. Ordre d'exécution
1. **Agent Architecte** → Stack, Schema, Stratégie Wiki/MapLibre.
2. **Agent Contenu** → JSON des 40 lieux (avec le piège Wiki manquant).
3. **Agent Back-end** (si Strapi).
4. **Agent Front-end** → SvelteKit, MapLibre, Mécanique de score, Écrans éducatifs (Cas A & B).
5. **Agent QA** → Audit, test du message de lacune documentaire, rapport.
---
## 8. Livrables finaux
1. Dépôt Git complet.
2. JSON de 40 lieux (avec la structure `wikidata_id: null` pour tester la lacune).
3. Rapport d'audit OKI.
4. Guide de déploiement auto-hébergé (SvelteKit + Tile Server).
5. Guide de contribution ("Comment ajouter un lieu et lier sa page Wikidata").
```