23 Commits
main ... 1.0.0

Author SHA1 Message Date
fd49d9a147 Added boost asset 2025-06-02 08:48:06 +02:00
c4d0ba3f1c Fixed cli level selection and added 2 more levels 2025-06-02 08:24:29 +02:00
9a754e94be Added boosts system which change the snake speed 2025-05-27 14:58:57 +02:00
9c053fe61c Added snake_head.png support 2025-05-27 12:37:13 +02:00
c8a4a40618 Added multi level support, dynamic snake location from level 2025-05-27 11:50:20 +02:00
4798ec85a3 Added using snake size and snake growth 2025-05-20 14:35:47 +02:00
d694422e66 Updated README 2025-05-20 13:13:49 +02:00
f36b376137 Rendu tp6 2025-05-20 13:04:52 +02:00
48c0bd0f96 Improving count fruit function 2025-05-19 16:15:53 +02:00
7b0f8f28e0 Rendu TP5 2025-05-19 16:06:59 +02:00
f16b505965 Update game.c 2025-05-14 15:55:10 +02:00
fdb80a7cc2 Rendu tp4 2025-05-14 15:50:48 +02:00
fc00084d03 remove unecessary include 2025-05-14 14:46:40 +02:00
197de63bde Updated README 2025-05-14 14:25:39 +02:00
cb05d9710b Rendu tp3 2025-05-14 14:15:45 +02:00
a9ed5e2e01 Initial commit for tp2 2025-05-09 08:46:25 +02:00
cc53a75b39 Added gitignore 2025-03-26 10:44:43 +01:00
7f68bd2e79 Removed useless function 2025-03-26 10:43:07 +01:00
178aea9af9 Added license file 2025-03-26 10:17:43 +01:00
07cf8c86c3 Added README 2025-03-26 10:10:36 +01:00
26e27b3fe9 Updated house 2025-03-26 09:56:06 +01:00
c4adaa2cf6 First version of the house 2025-03-26 09:34:52 +01:00
a39fd44d3a First commit 2025-03-26 09:05:12 +01:00
18 changed files with 1898 additions and 71 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
*.o
game

675
LICENSE.md Normal file
View File

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

35
Makefile Normal file
View File

@@ -0,0 +1,35 @@
# Compiler
CC = gcc
# Compiler flags
CFLAGS = -Wall -pedantic -ansi
# Linker flags
LDFLAGS = -lMLV
# Target executable
TARGET = game
# Source files
SRCS = game.c grid.c snake.c
# Object files
OBJS = $(SRCS:.c=.o)
# Default target
all: $(TARGET)
# Link the target executable
$(TARGET): $(OBJS)
$(CC) $(OBJS) -o $(TARGET) $(LDFLAGS)
# Compile source files to object files
%.o: %.c
$(CC) $(CFLAGS) -c $< -o $@
# Clean up build files
clean:
rm -f $(OBJS) $(TARGET)
# Phony targets
.PHONY: all clean

107
README-fr.md Normal file
View File

@@ -0,0 +1,107 @@
# Jeu Snake 2025
[![en](https://img.shields.io/badge/lang-en-red.svg)](https://git.esiee.fr/frequela/snake2025/-/blob/tp6/README.md)
[![fr](https://img.shields.io/badge/lang-fr-green.svg)](https://git.esiee.fr/frequela/snake2025/-/blob/tp6/README-fr.md)
Ce projet est un jeu snake basé sur une grille utilisant la bibliothèque graphique MLV. La grille représente un plateau de jeu avec des murs, des espaces vides, des fruits et un serpent. Le programme affiche la grille dans une fenêtre graphique et attend une interaction de l'utilisateur.
## Fonctionnalités
- Affiche une grille avec des murs, des espaces vides, des fruits et un serpent.
- Utilise la bibliothèque graphique MLV pour le rendu graphique.
- Assure que les blocs en dehors de la grille sont affichés en noir.
- Permet à l'utilisateur de quitter le programme en appuyant sur la touche ESC.
- Implémente un serpent dynamique utilisant une liste chaînée pour ses segments.
- Gère le mouvement du serpent en mettant à jour la position de la tête et en déplaçant tous les segments en conséquence.
- Permet au serpent de grandir lorsqu'il mange des fruits.
## Représentation de la Grille
- La grille est représentée comme un tableau 2D de caractères :
- `'w'` pour les murs.
- `' '` (espace) pour les espaces vides.
- `'f'` pour les fruits.
- `'s'` pour le serpent.
## Représentation du Serpent
- Le serpent est implémenté comme une liste chaînée de segments (`Position`), où :
- Chaque segment a des coordonnées `x` et `y`.
- Le pointeur `next` relie le segment suivant dans le serpent.
- Le mouvement du serpent est géré en :
- Ajoutant une nouvelle tête en fonction de la direction actuelle.
- Déplaçant tous les segments pour suivre la tête.
- Supprimant la queue sauf si le serpent mange un fruit.
## Dépendances
- GCC (GNU Compiler Collection)
- MLV (Mini Library for Visualization)
## Installation
### Installer MLV sur Ubuntu
1. Mettez à jour votre liste de paquets et installez les paquets requis :
```sh
sudo apt-get update
sudo apt-get install build-essential gcc make libmlv3-dev
```
### Compiler le Programme
1. Clonez le dépôt ou téléchargez le code source.
2. Naviguez vers le répertoire contenant le `Makefile`.
3. Exécutez la commande suivante pour compiler le programme :
```sh
make
```
Cela compilera les fichiers sources et créera un exécutable nommé `game` dans le répertoire `build`.
## Utilisation
1. Après avoir compilé le programme, exécutez l'exécutable :
```sh
./game
```
2. Une fenêtre s'ouvrira affichant la grille. Les blocs en dehors de la grille apparaîtront en noir. Utilisez les flèches directionnelles pour contrôler le serpent. Appuyez sur la touche ESC pour fermer la fenêtre.
## Logique du Jeu
- **Mouvement du Serpent** :
- Le serpent se déplace dans la direction actuelle, en mettant à jour la position de sa tête et en déplaçant tous les segments.
- Si le serpent mange un fruit, il grandit en ajoutant un nouveau segment sans supprimer la queue.
- Si le serpent entre en collision avec un mur ou lui-même, le jeu se termine.
- **Mise à Jour de la Grille** :
- La grille est mise à jour pour refléter la nouvelle position du serpent après chaque mouvement.
- Les fruits sont supprimés de la grille lorsqu'ils sont mangés par le serpent.
- **Condition de Victoire** :
- Le joueur gagne lorsque tous les fruits sur la grille sont collectés.
- **Condition de Défaite** :
- Le jeu se termine si le serpent entre en collision avec un mur ou lui-même.
## Nettoyage
Pour nettoyer les fichiers de compilation, exécutez :
```sh
make clean
```
Cela supprimera les fichiers objets et l'exécutable.
## Licence
Ce projet est sous licence GPLv3. Pour plus de détails, voir [Licence GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html).
## Auteurs
- Alex Frequelin (light_emerald@aostia.com)
## Remerciements
- Adrien Boussicault et Marc Zipstein pour la bibliothèque MLV.
- ESIEE Paris pour les supports de cours et les conseils.

156
README.md
View File

@@ -1,93 +1,107 @@
# snake2025
# Snake 2025 Game
[![en](https://img.shields.io/badge/lang-en-red.svg)](https://git.esiee.fr/frequela/snake2025/-/blob/tp6/README.md)
[![fr](https://img.shields.io/badge/lang-fr-green.svg)](https://git.esiee.fr/frequela/snake2025/-/blob/tp6/README-fr.md)
This project is a simple grid-based snake game using the MLV graphics library. The grid represents a game board with walls, empty spaces, fruits, and a snake. The program displays the grid in a graphical window and waits for user interaction.
## Features
## Getting started
- Displays a grid with walls, empty spaces, fruits, and a snake.
- Uses the MLV graphics library for graphical rendering.
- Ensures that blocks outside the grid are displayed as black.
- Allows the user to quit the program by pressing the ESC key.
- Implements a dynamic snake using a linked list for its segments.
- Handles snake movement by updating the head position and shifting all segments accordingly.
- Supports snake growth when eating fruits.
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
## Grid Representation
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
- The grid is represented as a 2D array of characters:
- `'w'` for walls.
- `' '` (space) for empty spaces.
- `'f'` for fruits.
- `'s'` for the snake.
## Add your files
## Snake Representation
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
- The snake is implemented as a linked list of segments (`Position` structures), where:
- Each segment has `x` and `y` coordinates.
- The `next` pointer links to the next segment in the snake.
- The snake's movement is handled by:
- Adding a new head based on the current direction.
- Shifting all segments to follow the head.
- Removing the tail unless the snake eats a fruit.
```
cd existing_repo
git remote add origin https://git.esiee.fr/frequela/snake2025.git
git branch -M main
git push -uf origin main
```
## Dependencies
## Integrate with your tools
- [ ] [Set up project integrations](https://git.esiee.fr/frequela/snake2025/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
***
# Editing this README
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
## Suggestions for a good README
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information.
## Name
Choose a self-explaining name for your project.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
- GCC (GNU Compiler Collection)
- MLV (Mini Library for Visualization)
## Installation
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
### Installing MLV on Ubuntu
1. Update your package list and install the required packages:
```sh
sudo apt-get update
sudo apt-get install build-essential gcc make libmlv3-dev
```
### Building the Program
1. Clone the repository or download the source code.
2. Navigate to the directory containing the `Makefile`.
3. Run the following command to build the program:
```sh
make
```
This will compile the source files and create an executable named `game` in the `build` directory.
## Usage
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
1. After building the program, run the executable:
```sh
./game
```
## Roadmap
If you have ideas for releases in the future, it is a good idea to list them in the README.
2. A window will open displaying the grid. Blocks outside the grid will appear black. Use the arrow keys to control the snake. Press the ESC key to close the window.
## Contributing
State if you are open to contributions and what your requirements are for accepting them.
## Game Logic
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
- **Snake Movement**:
- The snake moves in the current direction, updating its head position and shifting all segments.
- If the snake eats a fruit, it grows by adding a new segment without removing the tail.
- If the snake collides with a wall or itself, the game ends.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
- **Grid Updates**:
- The grid is updated to reflect the snake's new position after each move.
- Fruits are removed from the grid when eaten by the snake.
## Authors and acknowledgment
Show your appreciation to those who have contributed to the project.
- **Winning Condition**:
- The player wins when all fruits on the grid are collected.
- **Losing Condition**:
- The game ends if the snake collides with a wall or itself.
## Cleaning Up
To clean up the build files, run:
```sh
make clean
```
This will remove the object files and the executable.
## License
For open source projects, say how it is licensed.
## Project status
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
This project is licensed under the GPLv3 License. For more details, see [GPLv3 License](https://www.gnu.org/licenses/gpl-3.0.en.html).
## Authors
- Alex Frequelin (light_emerald@aostia.com)
## Acknowledgments
- Adrien Boussicault and Marc Zipstein for the MLV library.
- ESIEE Paris for the course materials and guidance.

BIN
assets/boost.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

BIN
assets/fruit.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 KiB

BIN
assets/grass.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 683 KiB

BIN
assets/wall.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

294
game.c Normal file
View File

@@ -0,0 +1,294 @@
#define _POSIX_C_SOURCE 200809L
#include <MLV/MLV_all.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "grid.h"
#include "snake.h"
#define BASE_SPEED 6
void print_help()
{
printf("Usage: snake2025 [OPTIONS]\n");
printf("Options:\n");
printf(" -h, --help Display this help message\n");
printf(" -i, --input FILE Load initial grid configuration from FILE\n");
printf("\n");
printf("This is a simple snake game. Use the arrow keys to control the snake.\n");
printf("Press ESC to exit the game.\n");
}
int main(int argc, char *argv[])
{
FILE *stream;
char *buf = NULL;
size_t size_buf = 0;
int nbl, nbc, i;
int opt, option_index = 0;
int loop_count = 0, nb_fruit = 0, total_fruits = 0;
char *input_file = NULL;
int width = 640, height = 480;
MLV_Keyboard_button touche = MLV_KEYBOARD_NONE;
int initial_size = 0;
int current_level = 1;
int global_score = 0;
int previous_score = 0;
int speed = BASE_SPEED;
int boosts = 0;
int boost_spawn_timer = 0;
int boost_spawn_interval = 0;
int boost_duration = 0;
const int boost_duration_frames = 5 * 24;
Grid *g;
static struct option long_options[] = {
{"help", no_argument, 0, 'h'},
{"input", required_argument, 0, 'i'},
{0, 0, 0, 0}};
while ((opt = getopt_long(argc, argv, "hi:", long_options, &option_index)) != -1)
{
switch (opt)
{
case 'h':
print_help();
return 0;
case 'i':
input_file = optarg;
break;
default:
fprintf(stderr, "Unknown option. Use -h or --help for usage information.\n");
return 1;
}
}
while (1)
{
Snake *snake = new_snake();
previous_score = global_score;
if (input_file == NULL)
{
char level_file[256];
snprintf(level_file, sizeof(level_file), "levels/level%d", current_level);
input_file = level_file;
}
stream = fopen(input_file, "r");
if (!stream)
{
fprintf(stderr, "Error: unable to open file for level %d\n", current_level);
exit(EXIT_FAILURE);
}
nbl = count_nb_lines(stream);
rewind(stream);
nbc = getline(&buf, &size_buf, stream);
if (nbc == -1)
{
fprintf(stderr, "Error: malformed file\n");
free(buf);
fclose(stream);
exit(EXIT_FAILURE);
}
nbc--;
g = allocate_grid(nbl, nbc);
copy(buf, g->grid[0]);
for (i = 1; i < nbl; i++)
{
int size_tmp = getline(&buf, &size_buf, stream);
if (size_tmp != nbc + 1)
{
fprintf(stderr, "Error: inconsistent line length\n");
free(buf);
free_grid(g);
fclose(stream);
exit(EXIT_FAILURE);
}
copy(buf, g->grid[i]);
}
rewind(stream);
nb_fruit = count_fruits(stream, g);
total_fruits = nb_fruit;
if (nb_fruit == 0)
{
fprintf(stderr, "Error: no fruits in the grid\n");
free(buf);
free_grid(g);
fclose(stream);
exit(EXIT_FAILURE);
}
if (nb_fruit == -1)
{
fprintf(stderr, "Error: unable to count fruits\n");
free(buf);
free_grid(g);
fclose(stream);
exit(EXIT_FAILURE);
}
free(buf);
buf = NULL;
fclose(stream);
read_snake_from_grid(g, snake);
initial_size = snake->size;
MLV_create_window("SNAKE", "3R-IN1B", width, height);
MLV_change_frame_rate(24);
while (
MLV_get_event(
&touche, NULL, NULL,
NULL, NULL,
NULL, NULL, NULL,
NULL) == MLV_NONE ||
touche != MLV_KEYBOARD_ESCAPE)
{
Element result;
char stats[256];
MLV_clear_window(MLV_COLOR_BLACK);
loop_count = (loop_count + 1) % speed;
if (loop_count == 0)
{
if (boost_spawn_timer >= boost_spawn_interval)
{
int x, y;
do
{
x = rand() % g->nbc;
y = rand() % g->nbl;
} while (g->grid[y][x] != EMPTY);
g->grid[y][x] = BOOST;
boost_spawn_timer = 0;
boost_spawn_interval = 50 + rand() % BASE_SPEED;
}
else
{
boost_spawn_timer++;
}
result = move_snake(snake, g);
if (result == WALL || result == SNAKE)
{
if (result == WALL)
{
MLV_draw_text(width / 2 - 80, height / 2, "Game Over! You hit a wall.", MLV_COLOR_RED);
}
else if (result == SNAKE)
{
MLV_draw_text(width / 2 - 80, height / 2, "Game Over! You hit yourself.", MLV_COLOR_RED);
}
MLV_actualise_window();
MLV_wait_seconds(3);
global_score = previous_score;
break;
}
else if (result == BOOST)
{
boosts++;
boost_duration = boost_duration_frames;
speed = BASE_SPEED - boosts;
speed = (BASE_SPEED - boosts) > 1 ? (BASE_SPEED - boosts) : 1;
printf("Boost collected! Speed increased. Boost duration: %d frames\n", boost_duration);
}
else if (result == FRUIT)
{
Position *tail = snake->segments_list;
Position *prev = NULL;
int dx, dy;
while (tail->next != NULL)
{
prev = tail;
tail = tail->next;
}
dx = tail->x - (prev ? prev->x : tail->x);
dy = tail->y - (prev ? prev->y : tail->y);
add_segment(snake, tail->x + dx, tail->y + dy);
place_snake(g, snake);
nb_fruit--;
global_score++;
if (snake->size == initial_size + total_fruits)
{
MLV_draw_text(
width / 2 - 200, height / 2,
"You Win! All fruits collected. Proceeding to the next level.",
MLV_COLOR_GREEN);
MLV_actualise_window();
MLV_wait_seconds(3);
current_level++;
break;
}
}
}
if (boost_duration > 0)
{
boost_duration--;
if (boost_duration == 0)
{
boosts--;
speed = (BASE_SPEED - boosts) > 1 ? (BASE_SPEED - boosts) : 1;
printf("Boost expired. Speed reset. Active boosts: %d\n", boosts);
}
}
draw_grid(g);
snprintf(stats, sizeof(stats),
"Level: %d | Fruits Left: %d/%d | Score: %d | Snake Size: %d | Boosts: %d",
current_level, nb_fruit, total_fruits, global_score, snake->size, boosts);
MLV_draw_text(10, height - 20, stats, MLV_COLOR_WHITE);
MLV_actualise_window();
switch (touche)
{
case MLV_KEYBOARD_DOWN:
if (snake->dir != TOP)
snake->dir = BOTTOM;
break;
case MLV_KEYBOARD_UP:
if (snake->dir != BOTTOM)
snake->dir = TOP;
break;
case MLV_KEYBOARD_LEFT:
if (snake->dir != RIGHT)
snake->dir = LEFT;
break;
case MLV_KEYBOARD_RIGHT:
if (snake->dir != LEFT)
snake->dir = RIGHT;
break;
default:
break;
}
touche = MLV_KEYBOARD_NONE;
MLV_delay_according_to_frame_rate();
}
MLV_free_window();
free_grid(g);
free_snake(snake);
input_file = NULL;
if (touche == MLV_KEYBOARD_ESCAPE)
{
break;
}
}
return 0;
}

385
grid.c Normal file
View File

@@ -0,0 +1,385 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <MLV/MLV_all.h>
#include "grid.h"
#include "snake.h"
Grid *allocate_grid(int n, int m)
{
Grid *g = malloc(sizeof(Grid));
int i;
if (!g)
{
fprintf(stderr, "Error: could not allocate Grid.\n");
exit(EXIT_FAILURE);
}
g->nbl = n;
g->nbc = m;
g->grid = malloc(n * sizeof(char *));
if (!g->grid)
{
fprintf(stderr, "Error: could not allocate g->grid.\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++)
{
g->grid[i] = calloc(m + 2, sizeof(char));
if (!g->grid[i])
{
fprintf(stderr, "Error: could not allocate row.\n");
exit(EXIT_FAILURE);
}
}
return g;
}
void free_grid(Grid *g)
{
int i;
if (!g)
return;
for (i = 0; i < g->nbl; i++)
{
free(g->grid[i]);
}
free(g->grid);
free(g);
}
void debug_grid(Grid *g)
{
int i;
for (i = 0; i < g->nbl; i++)
{
printf("%s\n", g->grid[i]);
}
}
int compute_size(Grid *g, int w, int h)
{
int size_width = w / g->nbc;
int size_height = h / g->nbl;
return (size_width < size_height) ? size_width : size_height;
}
void draw_grid(Grid *g)
{
int i, j;
int window_width = MLV_get_window_width();
int window_height = MLV_get_window_height();
int cell_size = compute_size(g, window_width, window_height);
MLV_Image *image_wall, *image_fruit, *image_snake, *image_snake_head, *image_boost, *image_empty;
image_wall = MLV_load_image("./assets/wall.png");
image_fruit = MLV_load_image("./assets/fruit.png");
image_snake = MLV_load_image("./assets/snake.png");
image_snake_head = MLV_load_image("./assets/snake_head.png");
image_boost = MLV_load_image("./assets/boost.png");
image_empty = MLV_load_image("./assets/grass.png");
if (image_wall != NULL)
{
MLV_resize_image_with_proportions(image_wall, cell_size, cell_size);
}
if (image_fruit != NULL)
{
MLV_resize_image_with_proportions(image_fruit, cell_size, cell_size);
}
if (image_snake != NULL)
{
MLV_resize_image_with_proportions(image_snake, cell_size, cell_size);
}
if (image_snake_head != NULL)
{
MLV_resize_image_with_proportions(image_snake_head, cell_size, cell_size);
}
if (image_boost != NULL)
{
MLV_resize_image_with_proportions(image_boost, cell_size, cell_size);
}
if (image_empty != NULL)
{
MLV_resize_image_with_proportions(image_empty, cell_size, cell_size);
}
MLV_draw_filled_rectangle(0, 0, window_width, window_height, MLV_COLOR_BLACK);
for (i = 0; i < g->nbl; i++)
{
for (j = 0; j < g->nbc; j++)
{
int x = j * cell_size;
int y = i * cell_size;
switch (g->grid[i][j])
{
case WALL:
if (image_wall == NULL)
{
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_BROWN);
}
else
{
MLV_draw_image(image_wall, x, y);
}
break;
case EMPTY:
if (image_empty != NULL)
{
MLV_draw_image(image_empty, x, y);
}
else
{
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_WHITE);
}
break;
case FRUIT:
if (image_fruit == NULL)
{
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_RED);
}
else
{
MLV_draw_image(image_fruit, x, y);
}
break;
case SNAKE:
if (image_snake == NULL)
{
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_GREEN);
}
else
{
MLV_draw_image(image_snake, x, y);
}
break;
case SNAKEHEAD:
if (image_snake == NULL)
{
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_GREEN);
}
else
{
MLV_draw_image(image_snake_head, x, y);
}
break;
case BOOST:
if (image_boost == NULL)
{
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_YELLOW);
}
else
{
MLV_draw_image(image_boost, x, y);
}
break;
default:
MLV_draw_filled_rectangle(x, y, cell_size, cell_size, MLV_COLOR_BLACK);
break;
}
}
}
}
void place_snake(Grid *g, struct SnakeStruct *snake)
{
Position *current = snake->segments_list;
if (current != NULL)
{
g->grid[current->y][current->x] = SNAKEHEAD;
current = current->next;
}
while (current != NULL)
{
g->grid[current->y][current->x] = SNAKE;
current = current->next;
}
}
Element move_snake(struct SnakeStruct *snake, Grid *g)
{
Position *tail = snake->segments_list;
Position *head;
Element element_at_head;
while (tail->next != NULL)
{
tail = tail->next;
}
g->grid[tail->y][tail->x] = EMPTY;
crawl(snake, g);
head = snake->segments_list;
element_at_head = g->grid[head->y][head->x];
g->grid[head->y][head->x] = SNAKEHEAD;
if (head->next != NULL)
{
g->grid[head->next->y][head->next->x] = SNAKE;
}
return element_at_head;
}
int count_nb_lines(FILE *stream)
{
int count = 0;
char buffer[256];
while (fgets(buffer, sizeof(buffer), stream))
{
count++;
}
rewind(stream);
return count;
}
int count_fruits(FILE *stream, Grid *g)
{
int i, j, nb_fruit = 0;
for (i = 0; i < g->nbl; i++)
{
if (!fgets(g->grid[i], g->nbc + 2, stream))
{
fprintf(stderr, "Error: Stream does not contain enough lines\n");
exit(EXIT_FAILURE);
}
g->grid[i][strcspn(g->grid[i], "\n")] = '\0';
for (j = 0; j < g->nbc; j++)
{
if (g->grid[i][j] == FRUIT)
{
nb_fruit++;
}
}
}
return nb_fruit;
}
void copy(const char *src, char *dst)
{
int i = 0;
while (src[i] != '\0' && src[i] != '\n')
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
}
static bool are_adjacent(Position *a, Position *b)
{
return (a->x == b->x && abs(a->y - b->y) == 1) ||
(a->y == b->y && abs(a->x - b->x) == 1);
}
int is_snake_connected(struct SnakeStruct *snake)
{
Position *current = snake->segments_list;
while (current && current->next)
{
if (!are_adjacent(current, current->next))
{
return 0;
}
current = current->next;
}
return 1;
}
void read_snake_from_grid(Grid *g, struct SnakeStruct *snake)
{
Position *positions = malloc(g->nbl * g->nbc * sizeof(Position));
int positions_count = 0;
Position *head = NULL;
Position *current;
int i;
int *used = NULL;
for (i = 0; i < g->nbl; i++)
{
int j;
for (j = 0; j < g->nbc; j++)
{
if (g->grid[i][j] == SNAKE || g->grid[i][j] == SNAKEHEAD)
{
positions[positions_count].x = j;
positions[positions_count].y = i;
positions[positions_count].next = NULL;
if (g->grid[i][j] == SNAKEHEAD)
{
head = &positions[positions_count];
}
positions_count++;
}
}
}
if (head == NULL)
{
fprintf(stderr, "Error: Snake head (S) not found in the grid.\n");
free(positions);
exit(EXIT_FAILURE);
}
used = malloc(positions_count * sizeof(int));
if (!used) {
fprintf(stderr, "Error: Could not allocate memory for used array.\n");
free(positions);
exit(EXIT_FAILURE);
}
for (i = 0; i < positions_count; i++)
{
used[i] = 0;
}
add_segment(snake, head->x, head->y);
used[head - positions] = 1;
current = head;
while (1)
{
int found = 0;
int j;
for (j = 0; j < positions_count; j++)
{
if (!used[j] && are_adjacent(current, &positions[j]))
{
add_segment(snake, positions[j].x, positions[j].y);
used[j] = 1;
current = &positions[j];
found = 1;
break;
}
}
if (!found)
{
break;
}
}
for (i = 0; i < positions_count; i++)
{
if (!used[i])
{
fprintf(stderr, "Error: Snake is not fully connected in the grid.\n");
free(positions);
exit(EXIT_FAILURE);
}
}
snake->dir = determine_initial_direction(g, snake->segments_list);
free(positions);
free(used);
}

40
grid.h Normal file
View File

@@ -0,0 +1,40 @@
#ifndef GRID_H
#define GRID_H
#include <stdio.h>
struct SnakeStruct;
struct GridStruct
{
char **grid;
int nbl;
int nbc;
};
typedef struct GridStruct Grid;
typedef enum
{
WALL = 'w',
EMPTY = ' ',
FRUIT = 'f',
SNAKE = 's',
SNAKEHEAD = 'S',
BOOST = 'b'
} Element;
Grid *allocate_grid(int n, int m);
void free_grid(Grid *g);
void debug_grid(Grid *g);
int compute_size(Grid *g, int w, int h);
void draw_grid(Grid *g);
void place_snake(Grid *g, struct SnakeStruct *snake);
Element move_snake(struct SnakeStruct *snake, Grid *g);
int count_nb_lines(FILE *stream);
int count_fruits(FILE *stream, Grid *g);
void copy(const char *src, char *dst);
int is_snake_connected(struct SnakeStruct *snake);
void read_snake_from_grid(Grid *g, struct SnakeStruct *snake);
#endif /* GRID_H */

22
levels/level1 Normal file
View File

@@ -0,0 +1,22 @@
w w
f
ssssS
f f
f
wwwwwwwwww
f
f f
f
w w

25
levels/level2 Normal file
View File

@@ -0,0 +1,25 @@
w w
f
f f
f
wwwwwwwwww
Sssssw w w
w f w
wwwwww w
w
w
f w
w
f f w
w
f w
w w
w
w
w

22
levels/level3 Normal file
View File

@@ -0,0 +1,22 @@
w w
w
ssssS w
w f
w
w
w
w f
f w
wwwwwwwwwwwwwwwwwwwwwwwww wwwwwwwww
f
w w

22
levels/level4 Normal file
View File

@@ -0,0 +1,22 @@
w w
w
f w
ssssS w
wwwwwwwwww
f
w
w
w
www w
f w f
w
w
f
wwwwwww
f
w w

147
snake.c Normal file
View File

@@ -0,0 +1,147 @@
#include <stdlib.h>
#include "grid.h"
#include "snake.h"
Snake *new_snake(void)
{
Snake *snake = (Snake *)malloc(sizeof(Snake));
if (snake == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
snake->size = 0;
snake->segments_list = NULL;
snake->dir = RIGHT;
return snake;
}
void add_segment(Snake *snake, int x, int y)
{
Position *new_segment = (Position *)malloc(sizeof(Position));
if (new_segment == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
new_segment->x = x;
new_segment->y = y;
new_segment->next = NULL;
if (snake->segments_list == NULL)
{
snake->segments_list = new_segment;
}
else
{
Position *current = snake->segments_list;
while (current->next != NULL)
{
current = current->next;
}
current->next = new_segment;
}
snake->size++;
}
void free_snake(Snake *snake)
{
Position *current = snake->segments_list;
while (current != NULL)
{
Position *next = current->next;
free(current);
current = next;
}
free(snake);
}
void debug_snake(Snake *snake)
{
Position *current = snake->segments_list;
printf("Snake segments:\n");
while (current != NULL)
{
printf(" (%d, %d)\n", current->x, current->y);
current = current->next;
}
printf("Snake size: %d\n", snake->size);
}
void crawl(Snake *snake, struct GridStruct *g)
{
Position *new_head = (Position *)malloc(sizeof(Position));
Position *current;
if (new_head == NULL)
{
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
new_head->x = snake->segments_list->x;
new_head->y = snake->segments_list->y;
switch (snake->dir)
{
case LEFT:
new_head->x = (new_head->x - 1 + g->nbc) % g->nbc;
break;
case RIGHT:
new_head->x = (new_head->x + 1) % g->nbc;
break;
case TOP:
new_head->y = (new_head->y - 1 + g->nbl) % g->nbl;
break;
case BOTTOM:
new_head->y = (new_head->y + 1) % g->nbl;
break;
}
new_head->next = snake->segments_list;
snake->segments_list = new_head;
current = snake->segments_list;
while (current->next != NULL && current->next->next != NULL)
{
current = current->next;
}
free(current->next);
current->next = NULL;
}
Direction determine_initial_direction(struct GridStruct *g, Position *head)
{
int x = head->x;
int y = head->y;
printf("Determining initial direction from position (%d, %d)\n", x, y);
if (x + 1 < g->nbc && g->grid[y][x + 1] != WALL && g->grid[y][x + 1] != SNAKE)
{
printf("Direction: RIGHT\n");
return RIGHT;
}
if (y + 1 < g->nbl && g->grid[y + 1][x] != WALL && g->grid[y + 1][x] != SNAKE)
{
printf("Direction: BOTTOM\n");
return BOTTOM;
}
if (x - 1 >= 0 && g->grid[y][x - 1] != WALL && g->grid[y][x - 1] != SNAKE)
{
printf("Direction: LEFT\n");
return LEFT;
}
if (y - 1 >= 0 && g->grid[y - 1][x] != WALL && g->grid[y - 1][x] != SNAKE)
{
printf("Direction: TOP\n");
return TOP;
}
printf("Default direction: BOTTOM\n");
return BOTTOM;
}

37
snake.h Normal file
View File

@@ -0,0 +1,37 @@
#ifndef SNAKE_H
#define SNAKE_H
struct GridStruct;
typedef struct Position
{
int x;
int y;
struct Position *next;
} Position;
typedef enum
{
TOP,
BOTTOM,
LEFT,
RIGHT
} Direction;
struct SnakeStruct
{
Position *segments_list;
int size;
Direction dir;
};
typedef struct SnakeStruct Snake;
Snake *new_snake(void);
void add_segment(Snake *snake, int x, int y);
void free_snake(Snake *snake);
void debug_snake(Snake *snake);
void crawl(Snake *snake, struct GridStruct *g);
Direction determine_initial_direction(struct GridStruct *g, Position *head);
#endif /* SNAKE_H */