Compare commits

...

117 Commits

Author SHA1 Message Date
83c52a9a5f Fix multiplayer crash and remove debug display 2024-12-12 15:58:29 +01:00
ad85095721 Yolo dans la main 2024-12-12 14:39:14 +01:00
Félix MARQUET
f38d39bed6 Merge pull request #21 from BreizhHardware/Fix-exit-code-3
Try to fix it don't work but fuck it
2024-12-12 14:37:24 +01:00
64a83518d0 Try to fix it don't work but fuck it 2024-12-12 14:36:20 +01:00
Félix MARQUET
34aa5490cb Merge pull request #20 from BreizhHardware/collision
add collisions
2024-12-12 14:23:25 +01:00
Clément Fouché
100a6b91d1 add collisions 2024-12-12 14:21:32 +01:00
Félix MARQUET
4745f6fb19 Merge pull request #19 from BreizhHardware/fix-arg
fix arg
2024-12-12 14:13:29 +01:00
Clément Fouché
ccefcb8c87 fix arg 2024-12-12 14:07:08 +01:00
17e65843b0 Fix CMake for static build 2024-12-12 10:20:53 +01:00
Félix MARQUET
4d4447d250 Merge pull request #18 from BreizhHardware/FIX-CI
Switch CI to fedora
2024-12-12 10:15:50 +01:00
479ae3c4da Switch CI to ubuntu but contenerized fedora 2024-12-12 10:14:20 +01:00
bf48cdf306 Switch CI to ubuntu but contenerized fedora 2024-12-12 10:14:13 +01:00
e2cc90d8a5 Switch CI to fedora 2024-12-12 10:00:27 +01:00
Félix MARQUET
d5520ded03 Merge pull request #16 from BreizhHardware/fix
fix arg
2024-12-12 09:52:23 +01:00
Clément Fouché
21f014a503 fix arg 2024-12-12 09:51:57 +01:00
6fd472fb24 Add video background 2024-12-12 09:50:03 +01:00
Félix MARQUET
62de143515 Merge pull request #15 from BreizhHardware/online
Online
2024-12-12 09:47:42 +01:00
14ba3cf431 Fix CMakeLists.txt 2024-12-12 09:46:37 +01:00
3609bc0a4f Fix CI 2024-12-12 09:39:00 +01:00
e15c20982e Fix wird char in message 2024-12-12 09:37:23 +01:00
bc6e718cfb Add CI When pr 2024-12-12 09:30:30 +01:00
93d88efbd4 Shark is working in multiplayer 2024-12-12 09:27:17 +01:00
Félix MARQUET
b9966daac0 Merge pull request #14 from BreizhHardware/C'EST-QUOI-CETTE-SALLE-DE-MERDE-LA
Le requin il parle LOL
2024-12-12 08:58:06 +01:00
35454b2eba Début du shark en network 2024-12-12 08:56:00 +01:00
StevSpotted
72fa9fede5 Fix quit 2024-12-12 08:44:53 +01:00
f57318d739 Début du shark en network 2024-12-12 08:39:28 +01:00
98e9fedd71 Wahla ça marche 2024-12-10 17:16:09 +01:00
Félix MARQUET
02864c8e5d Merge pull request #13 from BreizhHardware/gawr-gura
Gawr gura
2024-12-10 17:12:54 +01:00
cfouche
57750176c4 Merge branch 'online' into gawr-gura 2024-12-10 17:12:47 +01:00
7d0dccf7af NORMALEMENT ON SE VOIT LA OUI 2024-12-10 17:08:16 +01:00
8e181b5adf NORMALEMENT ON SE VOIT LA OUI 2024-12-10 17:06:59 +01:00
060d6cfbc7 NORMALEMENT ON SE VOIT 2024-12-10 17:03:07 +01:00
cffa9855d2 Maybe fix LOL V3 2024-12-10 16:46:28 +01:00
56f4347bb4 Maybe fix LOL V2 2024-12-10 16:36:26 +01:00
Clément Fouché
2b414bf08a ça fonctionne bis 2024-12-10 16:24:55 +01:00
0908e168f4 Maybe fix LOL 2024-12-10 16:23:53 +01:00
a1ad854c81 Fix wrong player list for dispaly in multi 2024-12-10 16:14:58 +01:00
Clément Fouché
ae80604f29 ça fonctionne (pas sur) 2024-12-10 15:49:30 +01:00
098931d8b7 Add quit if server is unreachable 2024-12-10 15:46:35 +01:00
Clément Fouché
0871724a30 ça fonctionne (pas sur) 2024-12-10 15:42:58 +01:00
StevSpotted
d4c8fc0504 Fsdqf 2024-12-10 15:29:20 +01:00
StevSpotted
37aa87a07f fix it, mechanic 2024-12-10 15:26:18 +01:00
5fb37df1ce Fix unable to quit 2024-12-10 15:25:09 +01:00
Clément Fouché
8b6264b7ba wip 2024-12-10 15:21:48 +01:00
34ef1c8ace Fix unable to quit 2024-12-10 15:16:26 +01:00
Clément Fouché
15631c95be wip 2024-12-10 15:16:23 +01:00
StevSpotted
e621bc711e azzfqeezd 2024-12-10 15:03:18 +01:00
4f65a2ab78 hjk,;lzfane ,hjv 2024-12-10 15:03:02 +01:00
d18937ddea Add try catch for the quit and rework the recover energy système 2024-12-10 14:53:24 +01:00
StevSpotted
dfecb8d663 Try to fix 2024-12-10 14:51:49 +01:00
b4ca99c4a2 Imporve thread creation 2024-12-10 14:26:09 +01:00
StevSpotted
0d922391a2 log thread 2024-12-10 14:09:29 +01:00
7eaf2ac23b Handle proper quit with quit message 2024-12-10 13:51:33 +01:00
Clément Fouché
bb7b7a86ec add fix wayland 2024-12-10 13:47:36 +01:00
91fb21ac79 hyubhvvyd jsgdsrc gvbn 2024-12-09 17:26:40 +01:00
StevSpotted
ff23a15f08 fix erreur de con fait par Felix 2024-12-09 17:25:34 +01:00
5dc0d4d386 add Dynamic ip in menu ta race le con j'en ai marre je veux mourrir 2024-12-09 16:55:43 +01:00
StevSpotted
d2d5626ef0 up 2024-12-09 16:50:59 +01:00
Clément Fouché
18072b7721 add shark 2024-12-09 16:50:36 +01:00
266a087349 Try to fix LOL V2 2024-12-09 16:26:18 +01:00
b60f2e8aef Try to fix LOL 2024-12-09 16:24:02 +01:00
Félix MARQUET
ca53de3f74 Merge pull request #12 from BreizhHardware/main
Main into online
2024-12-09 15:44:38 +01:00
Félix MARQUET
57a41c8b84 Merge pull request #11 from BreizhHardware/fix
Fix
2024-12-09 15:43:57 +01:00
Clément Fouché
513b7afb5c add arg 2024-12-09 15:43:06 +01:00
ef28f48388 Add unified coords to the multiplayer 2024-12-09 15:27:04 +01:00
1929235cb2 Reduce to 2500 fish 2024-12-09 14:53:41 +01:00
Félix MARQUET
9c1673bdf9 Merge pull request #10 from BreizhHardware/breizhhardware-online-merge-patch
Update online
2024-12-09 14:52:00 +01:00
34251c9e3f Fix merge main into online 2024-12-09 14:51:49 +01:00
Félix MARQUET
698fc50207 Merge branch 'online' into breizhhardware-online-merge-patch 2024-12-09 14:43:23 +01:00
StevSpotted
3c751fb72f Mouvements diagonales 2024-12-09 14:39:16 +01:00
Clément Fouché
95ecdcc619 fix 2024-12-09 14:33:54 +01:00
Félix MARQUET
ea99a02ed9 Merge pull request #9 from BreizhHardware/opti
FIx small bug
2024-12-09 14:31:25 +01:00
35ef088f72 Add keep alive 2024-12-09 14:28:56 +01:00
Clément Fouché
7631802cb3 fix args 2024-12-09 14:17:11 +01:00
Clément Fouché
c0a1b5f508 fix args 2024-12-09 14:14:43 +01:00
Clément Fouché
e99714f85b remove thread 2024-12-09 14:12:05 +01:00
fbc42ec500 Add bypass Menu 2024-12-09 14:09:40 +01:00
dd8c37a2c6 Add catch for sendMessage 2024-12-09 14:05:40 +01:00
Félix MARQUET
6b3ece56c4 Merge pull request #8 from BreizhHardware/sweep
Sweep
2024-12-09 13:58:51 +01:00
StevSpotted
b3dafa3208 up 2024-12-09 13:58:42 +01:00
cfouche
8ab2a82fac Merge branch 'main' into sweep 2024-12-09 13:58:19 +01:00
StevSpotted
200d12a67f Up 2024-12-09 13:57:21 +01:00
4f8250d913 Fix sticky border 2024-12-09 13:54:45 +01:00
f673b7f892 Fix crash when playerID = 0 2024-12-09 13:43:53 +01:00
Clément Fouché
ceeb72d56f change gitignore 2024-12-09 13:31:33 +01:00
bfd4f2f842 Fix unified coords 2024-12-08 17:33:09 +01:00
fb9df2ae08 Start adding capability to see other players 2024-12-08 17:26:03 +01:00
aed1033f43 Add unifed coord system 2024-12-06 16:33:13 +01:00
Félix MARQUET
e11a64fc2c Create LICENSE 2024-12-06 16:23:58 +01:00
1a369af88f Add unified player coords 2024-12-06 16:04:08 +01:00
db869b2cdf End of the base menu 2024-12-06 14:20:07 +01:00
4df48ec424 Add To do to the README.md 2024-12-06 13:58:32 +01:00
be0ae56c16 Add Join to the menu
# To do
[ ] Voir les autres joueurs
[ ] Id Incrémental pour les players
[ ] Récupération des infos des champs de text pour le join
[ ] Affichage de l'ip dans le champs d'host
[ ] Requin adversaire
2024-12-06 13:57:25 +01:00
7c49911eb4 New menu for multiplayer 2024-12-06 13:43:42 +01:00
4409024e5c Fix camera for the multiplayer 2024-12-06 13:33:14 +01:00
a4f6db4151 Fix camera for the multiplayer 2024-12-06 13:31:32 +01:00
StevSpotted
08629eb290 Fix 2024-12-06 13:07:00 +01:00
Clément Fouché
49dd133095 it works 2024-12-04 17:35:50 +01:00
9a2e8ba5fb First try with menu 2024-12-04 16:47:48 +01:00
Félix MARQUET
df0c67f03f Merge pull request #7 from BreizhHardware/breizhhardware-patch-1
Main into online
2024-12-04 16:35:46 +01:00
Félix MARQUET
adc70277d5 Merge branch 'online' into breizhhardware-patch-1 2024-12-04 16:35:31 +01:00
Félix MARQUET
0c4a4534d9 Merge pull request #6 from BreizhHardware/StevSpotted-patch-1
Fix error
2024-12-04 16:26:35 +01:00
eec440106a Fix playing TA RACE 2024-12-04 16:24:47 +01:00
e8c75aa187 Deplacement V1 2024-12-04 16:21:21 +01:00
9b166b509e Make player moved with the server instruction 2024-12-04 15:15:21 +01:00
8defdb1225 Restart from sratch using SDL2_net instead of home maid TCP Server and Client 2024-12-04 14:54:45 +01:00
Clément Fouché
244d08dc4b work in progress 2024-12-02 17:21:22 +01:00
724567537c Enhence client and server compatibility for Linux 2024-12-02 16:26:27 +01:00
48bc88059e Fix missing include 2024-12-02 15:08:24 +01:00
3828b51577 WIP Communication 2024-12-02 14:55:41 +01:00
Clément Fouché
b17c8a013e test 2024-12-02 14:36:48 +01:00
Clément Fouché
e05623c330 change gitignore 2024-11-12 11:57:29 +01:00
Clément Fouché
8ea4f64a75 fuck 2024-11-12 11:56:09 +01:00
9c92b826c3 Add TCPCLient and TCPServer 2024-11-12 11:37:57 +01:00
8d30a94fdf able to move again 2024-11-12 10:49:56 +01:00
bedb53f352 Add .vscode to gitignore 2024-11-12 10:19:03 +01:00
157a6895d7 Add seconds player 2024-11-12 10:13:29 +01:00
29 changed files with 8717 additions and 346 deletions

45
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,45 @@
name: Build and Test
on:
pull_request:
branches:
- main
- online
jobs:
build:
runs-on: ubuntu-latest
container:
image: fedora:latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up C++ environment
run: |
dnf install -y gcc gcc-c++ cmake make
- name: Install SDL2 dependencies
run: |
dnf install -y SDL2 SDL2-devel SDL2_image SDL2_image-devel SDL2_ttf SDL2_ttf-devel SDL2_net SDL2_net-devel SDL2_mixer SDL2_mixer-devel
- name: Clean build directory
run: rm -rf build
- name: Create build directory
run: mkdir build
- name: Configure CMake
run: cmake -S . -B build
- name: Build project
run: cmake --build build -- -j $(nproc)
- name: Check for warnings and errors
run: |
if grep -i "warning\|error" build/compile_commands.json; then
echo "Build contains warnings or errors"
exit 1
fi

19
.gitignore vendored
View File

@@ -41,4 +41,21 @@ build/
cmake-build-debug/
cmake-build-mingw/
cmake-build-debug
cmake-build-mingw
cmake-build-mingw
cmake-build-debug-clang
cmake-build-debug-gcc
cmake-build-debug-clang/
cmake-build-debug-gcc/
cmake-build-release-clang
cmake-build-release-clang/
cmake-build-release-gcc
cmake-build-release-gcc/
cmake-build-fedora
cmake-build-fedora/
cmake-build-debug-wsl
cmake-build-debug-wsl/
cmake-build-release-mingw
cmake-build-release-mingw/
# .vscode folder
.vscode/

View File

@@ -1,20 +0,0 @@
{
"configurations": [
{
"name": "Win32",
"includePath": [
"${workspaceFolder}/**"
],
"defines": [
"_DEBUG",
"UNICODE",
"_UNICODE"
],
"windowsSdkVersion": "10.0.22621.0",
"compilerPath": "cl.exe",
"cStandard": "c17",
"intelliSenseMode": "windows-msvc-x64"
}
],
"version": 4
}

63
.vscode/settings.json vendored
View File

@@ -1,63 +0,0 @@
{
"files.associations": {
"*.embeddedhtml": "html",
"vector": "cpp",
"atomic": "cpp",
"bit": "cpp",
"cctype": "cpp",
"charconv": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"compare": "cpp",
"concepts": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"cwchar": "cpp",
"exception": "cpp",
"format": "cpp",
"initializer_list": "cpp",
"ios": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"iterator": "cpp",
"limits": "cpp",
"locale": "cpp",
"memory": "cpp",
"mutex": "cpp",
"new": "cpp",
"ostream": "cpp",
"ratio": "cpp",
"stdexcept": "cpp",
"stop_token": "cpp",
"streambuf": "cpp",
"string": "cpp",
"system_error": "cpp",
"thread": "cpp",
"tuple": "cpp",
"type_traits": "cpp",
"typeinfo": "cpp",
"utility": "cpp",
"xfacet": "cpp",
"xiosbase": "cpp",
"xlocale": "cpp",
"xlocbuf": "cpp",
"xlocinfo": "cpp",
"xlocmes": "cpp",
"xlocmon": "cpp",
"xlocnum": "cpp",
"xloctime": "cpp",
"xmemory": "cpp",
"xstring": "cpp",
"xtr1common": "cpp",
"xutility": "cpp",
"functional": "cpp",
"list": "cpp",
"unordered_map": "cpp",
"xhash": "cpp"
}
}

48
.vscode/tasks.json vendored
View File

@@ -1,48 +0,0 @@
{
"version": "2.0.0",
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++.exe build active file",
"command": "C:\\msys64\\ucrt64\\bin\\g++.exe",
"args": [
"-fdiagnostics-color=always",
"-g",
"${file}",
"-o",
"${fileDirname}\\${fileBasenameNoExtension}.exe"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$gcc"
],
"group": "build",
"detail": "compiler: C:\\msys64\\ucrt64\\bin\\g++.exe"
},
{
"type": "cppbuild",
"label": "C/C++: cl.exe build active file",
"command": "cl.exe",
"args": [
"/Zi",
"/EHsc",
"/nologo",
"/Fe${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
],
"options": {
"cwd": "${fileDirname}"
},
"problemMatcher": [
"$msCompile"
],
"group": {
"kind": "build",
"isDefault": true
},
"detail": "Task generated by Debugger."
}
]
}

View File

@@ -4,13 +4,19 @@ project(bloubloulespoissons)
set(CMAKE_CXX_STANDARD 23)
# Ajouter le chemin de la bibliothèque SDL2
set(CMAKE_PREFIX_PATH "C:/SDL2")
if (WIN32)
set(CMAKE_PREFIX_PATH "C:/SDL2")
else()
set(CMAKE_PREFIX_PATH "/usr/local/lib/cmake/SDL2")
endif()
find_package(SDL2 REQUIRED)
find_package(SDL2_image REQUIRED)
find_package(SDL2_ttf REQUIRED)
find_package(SDL2_net REQUIRED)
find_package(SDL2_mixer REQUIRED)
include_directories(${SDL2_INCLUDE_DIRS} ${SDL2_IMAGE_INCLUDE_DIRS} ${SDL2_TTF_INCLUDE_DIRS})
include_directories(${SDL2_INCLUDE_DIRS} ${SDL2_IMAGE_INCLUDE_DIRS} ${SDL2_TTF_INCLUDE_DIRS} ${SDL2_NET_INCLUDE_DIRS})
add_executable(bloubloulespoissons main.cpp fish.cpp decors.cpp
camera.cpp
@@ -21,10 +27,18 @@ add_executable(bloubloulespoissons main.cpp fish.cpp decors.cpp
player.cpp
menu.h
menu.cpp
network/networking.cpp
network/networking.h
network/networking_client.cpp
network/networking_client.h
display.cpp
display.h
shark.cpp
shark.h
)
# Lier SDL2 et SDL2_image
target_link_libraries(bloubloulespoissons ${SDL2_LIBRARIES} -lSDL2_image -lSDL2_ttf)
target_link_libraries(bloubloulespoissons ${SDL2_LIBRARIES} SDL2::SDL2 SDL2_image::SDL2_image SDL2_ttf::SDL2_ttf SDL2_net::SDL2_net SDL2_mixer::SDL2_mixer)
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0")
@@ -35,4 +49,10 @@ if (WIN32)
else()
set_target_properties(bloubloulespoissons PROPERTIES LINK_FLAGS "/SUBSYSTEM:CONSOLE")
endif()
target_link_libraries(bloubloulespoissons ws2_32)
endif()
# Options pour la liaison statique en mode release
if (CMAKE_BUILD_TYPE STREQUAL "Release")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
endif()

674
LICENSE Normal file
View File

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

View File

@@ -1 +1,8 @@
# bloubloulespoissons
# bloubloulespoissons
# To do
[ ] Voir les autres joueurs
[ ] Id Incrémental pour les players
[ ] Récupération des infos des champs de text pour le join
[X] Affichage de l'ip dans le champs d'host (fonctionnalité retiré)
[ ] Requin adversaire

40
display.cpp Normal file
View File

@@ -0,0 +1,40 @@
//
// Created by BreizhHardware on 08/12/2024.
//
#include "display.h"
double calculateDistance(int x1, int y1, int x2, int y2) {
return std::sqrt(std::pow(x2 - x1, 2) + std::pow(y2 - y1, 2));
}
void displayNearbyPlayers(SDL_Renderer* renderer, TTF_Font* font, Player& currentPlayer, std::vector<Player>& players, double threshold) {
int currentX = currentPlayer.getUnifiedX();
int currentY = currentPlayer.getUnifiedY();
int offsetY = 90;
for (auto& player : players) {
if (&player == &currentPlayer) continue; // Skip the current player
int playerX = player.getUnifiedX();
int playerY = player.getUnifiedY();
double distance = calculateDistance(currentX, currentY, playerX, playerY);
if (distance <= threshold) {
std::string nearbyPlayerText = "Nearby Player: (" + std::to_string(playerX) + ", " + std::to_string(playerY) + ")";
SDL_Color textColor = {0, 255, 0};
SDL_Surface* textSurface = TTF_RenderText_Solid(font, nearbyPlayerText.c_str(), textColor);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_Rect textRect = {10, offsetY, textSurface->w, textSurface->h};
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
SDL_FreeSurface(textSurface);
SDL_DestroyTexture(textTexture);
// Affiche la 1ère image de playerV2-full.png
SDL_Rect playerRect = {69, 73, 112, 117};
SDL_Rect playerPosForRender = {playerX, playerY, 112, 117};
SDL_RenderCopy(renderer, player.getTexture(), &playerRect, &playerPosForRender);
offsetY += 20;
}
}
}

17
display.h Normal file
View File

@@ -0,0 +1,17 @@
//
// Created by BreizhHardware on 08/12/2024.
//
#ifndef DISPLAY_H
#define DISPLAY_H
#include <SDL2/SDL.h>
#include <SDL2/SDL_ttf.h>
#include <vector>
#include <cmath>
#include <string>
#include "player.h"
double calculateDistance(int x1, int y1, int x2, int y2);
void displayNearbyPlayers(SDL_Renderer* renderer, TTF_Font* font, Player& currentPlayer, std::vector<Player>& players, double threshold);
#endif //DISPLAY_H

View File

@@ -15,8 +15,14 @@ SDL_Renderer* renderer = nullptr;
SDL_Window* window = nullptr;
TTF_Font* font = nullptr;
int fishCount = 0;
int FISH_NUMBER = 1500;
int FISH_NUMBER = 2500;
std::vector<SDL_Texture*> texturesVector;
std::atomic<bool> running(true);
std::atomic<bool> game_running(false);
std::atomic<bool> isPlayingOnline(false);
std::atomic<bool> messageThreadRunning(false);
std::atomic<bool> isHost(false);
bool initEnvironment(SDL_Renderer* renderer) {
SDL_Surface* backgroundSurface = IMG_Load("../img/background.png");

10
env.h
View File

@@ -1,6 +1,7 @@
#ifndef ENV_H
#define ENV_H
#include <atomic>
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
@@ -11,6 +12,8 @@
#include <sys/stat.h>
#include <unistd.h>
class Player;
extern int windowWidth;
extern int windowHeight;
extern int playerBaseX;
@@ -26,6 +29,13 @@ extern TTF_Font* font;
extern int fishCount;
extern int FISH_NUMBER;
extern std::vector<SDL_Texture*> texturesVector;
extern std::atomic<bool> running;
extern std::atomic<bool> game_running;
extern std::atomic<bool> isPlayingOnline;
extern std::atomic<bool> messageThreadRunning;
extern std::vector<Player> players;
extern std::vector<Player> players_server;
extern std::atomic<bool> isHost;
bool initEnvironment(SDL_Renderer* renderer);
std::vector<SDL_Texture*> initTexture(SDL_Renderer* renderer);

View File

@@ -1,5 +1,31 @@
#include "fish.h"
Fish::Fish(const int x, const int y, const float vx, const float vy, std::vector<Fish> &school, const int id, const int width, const int height, SDL_Renderer* renderer, int biasdir, SDL_Texture* texture)
: x(x), y(y), vx(vx), vy(vy), school(school), id(id), width(width), height(height), biasdir(biasdir), texture(texture) {
// Constructor implementation
}
Fish::Fish(const Fish& other)
: x(other.x), y(other.y), vx(other.vx), vy(other.vy), school(other.school), id(other.id), texture(other.texture), width(other.width), height(other.height), biasdir(other.biasdir) {
// Additional initialization if needed
}
Fish& Fish::operator=(const Fish& other) {
if (this != &other) {
x = other.x;
y = other.y;
vx = other.vx;
vy = other.vy;
school = other.school;
id = other.id;
texture = other.texture;
width = other.width;
height = other.height;
biasdir = other.biasdir;
}
return *this;
}
void Fish::drawArrow(SDL_Renderer *renderer, int x, int y, float vx, float vy) {
const int arrowLength = 30; // Augmenter la longueur de la flèche
const int arrowWidth = 10; // Garder la largeur de la flèche constante
@@ -50,25 +76,47 @@ bool Fish::isClose(Fish &other) {
other.getY() >= y - PROTECTED_RANGE && other.getY() <= y + PROTECTED_RANGE);
}
void Fish::cycle() {
//std::cout << "Cycle " << cycle_count << " pour le poisson " << id << std::endl;
//std::cout << "Poisson Position: (" << x << ", " << y << ")" << std::endl;
//std::cout << "Vitesse: (" << vx << ", " << vy << ")" << std::endl;
void Fish::checkNeighborhood(Fish &other,float &xpos_avg, float &ypos_avg, float &xvel_avg, float &yvel_avg, int &neighboring_boids, float &close_dx, float &close_dy) {
if (isInView(other)) {
if (isClose(other)) {
close_dx += x - other.getX();
close_dy += y - other.getY();
}
xpos_avg += other.getX();
ypos_avg += other.getY();
xvel_avg += other.getVx();
yvel_avg += other.getVy();
neighboring_boids++;
}
}
void Fish::insertionSort(std::vector<Fish>& school) {
for (size_t i = 1; i < school.size(); ++i) {
Fish key = school[i];
int j = i - 1;
while (j >= 0 && Fish::SortByX(key, school[j])) {
school[j + 1] = school[j];
--j;
}
school[j + 1] = key;
}
}
void Fish::cycle(int iter) {
int neighboring_boids = 0;
float xvel_avg = 0, yvel_avg = 0, xpos_avg = 0, ypos_avg = 0, close_dx = 0, close_dy = 0;
for (Fish &schoolIt: school) {
if (schoolIt.getId() != id) {
if (isInView(schoolIt)) {
if (isClose(schoolIt)) {
close_dx += x - schoolIt.getX();
close_dy += y - schoolIt.getY();
}
xpos_avg += schoolIt.getX();
ypos_avg += schoolIt.getY();
xvel_avg += schoolIt.getVx();
yvel_avg += schoolIt.getVy();
neighboring_boids++;
}
for (int i = iter; i < school.size(); i++) {
if (school[i].getId() != id) {
if (school[i].getX() - VISUAL_RANGE > x + VISUAL_RANGE) { break; }
checkNeighborhood(school[i], xpos_avg, ypos_avg, xvel_avg, yvel_avg, neighboring_boids, close_dx, close_dy);
}
}
for (int i = iter - 1; i >= 0; i--) {
if (school[i].getId() != id) {
if (school[i].getX() + VISUAL_RANGE < x - VISUAL_RANGE) { break; }
checkNeighborhood(school[i], xpos_avg, ypos_avg, xvel_avg, yvel_avg, neighboring_boids, close_dx, close_dy);
}
}
if (neighboring_boids > 0) {
@@ -111,17 +159,4 @@ void Fish::cycle() {
}
x += vx;
y += vy;
//cycle_count++;
//std::cout << "Updated Position: (" << x << ", " << y << ")" << std::endl;
//std::cout << "Updated Vitesse: (" << vx << ", " << vy << ")" << std::endl;
}
Fish::Fish(const int x, const int y, const float vx, const float vy, std::vector<Fish> &school, const int id,
const int width, const int height, SDL_Renderer *renderer, int biasdir,
SDL_Texture *texture): x(x), y(y), vx(vx), vy(vy), school(school), id(id), width(width), height(height),
texture(texture), biasdir(biasdir) {
if (!texture) {
std::cerr << "Erreur de chargement de la texture: " << IMG_GetError() << std::endl;
}
}
}

33
fish.h
View File

@@ -20,21 +20,20 @@ private:
const float MAX_SPEED = 13;
const float MIN_SPEED = 0.6;
const float BIASVALUE = 0.001;
//const float MAXBIAS = 0.01;
float x, y;
float vx, vy;
std::vector<Fish> &school;
int id;
SDL_Texture* texture;
//int cycle_count = 0;
int width, height;
int biasdir = 1;
void checkNeighborhood(Fish &other, float &xpos_avg, float &ypos_avg, float &xvel_avg, float &yvel_avg, int &neighboring_boids, float &
close_dx, float &close_dy);
;
public:
Fish(const int x, const int y, const float vx, const float vy,std::vector<Fish> &school, const int id,const int width,const int height, SDL_Renderer* renderer,int biasdir, SDL_Texture* texture);
Fish(const int x, const int y, const float vx, const float vy, std::vector<Fish> &school, const int id, const int width, const int height, SDL_Renderer* renderer, int biasdir, SDL_Texture* texture);
~Fish() = default;
float getX() const { return x; };
@@ -43,28 +42,24 @@ public:
float getVy() const { return vy; };
int getId() const { return id; };
void draw(SDL_Renderer* renderer);
void drawArrow(SDL_Renderer* renderer, int x, int y, float vx, float vy);
void cycle();
void cycle(int iter);
bool isInView(Fish& other);
bool isClose(Fish& other);
SDL_Texture* getTexture() const { return this->texture; };
SDL_Rect getRect() const { return {static_cast<int>(this->x), static_cast<int>(this->y), this->width, this->height}; };
Fish& operator=(const Fish& other) {
if (this != &other) {
// Les membres constants ne peuvent pas être assignés, donc nous ne les assignons pas ici
// school est une référence, donc nous ne pouvons pas la réassigner non plus
// Si vous avez d'autres membres non constants, vous pouvez les assigner ici
}
return *this;
static bool SortByX(const Fish &a, const Fish &b) {
return a.getX() < b.getX();
}
// Définir explicitement le constructeur de copie et l'opérateur d'affectation par déplacement si nécessaire
Fish(const Fish& other) = delete;
Fish(Fish&& other) = default;
Fish& operator=(Fish&& other) = default;
static void insertionSort(std::vector<Fish>& school) ;
// Copy constructor
Fish(const Fish& other);
// Copy assignment operator
Fish& operator=(const Fish& other);
};
#endif //FISH_H

6461
img/shark.pdn Normal file

File diff suppressed because one or more lines are too long

BIN
img/shark.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 43 KiB

631
main.cpp
View File

@@ -1,52 +1,122 @@
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_net.h>
#include <SDL2/SDL_mixer.h>
#include <iostream>
#include <vector>
#include <future>
#include <thread>
#include <mutex>
#include <atomic>
#include <cstdlib>
#include <algorithm>
#include <random>
#include "fish.h"
#include "decors.h"
#include "camera.h"
#include "display.h"
#include "env.h"
#include "player.h"
#include "menu.h"
#include "network/networking.h"
#include "network/networking_client.h"
#include "shark.h"
#include <system_error>
std::mutex mtx;
std::atomic<bool> running(true);
std::atomic<bool> menuRunning(true);
std::mutex coutMutex;
SDL_Texture* playerTexture = nullptr;
SDL_Texture* fishTextures[100]; // Adjust the size as needed
std::vector<Fish> school;
std::vector<Player> players;
std::vector<Player> players_server;
struct ThreadInfo {
std::thread::id id;
std::string functionName;
bool isRunning;
};
std::vector<ThreadInfo> threadInfos;
bool initSDL();
void handleQuit();
void renderScene(Player player, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks, const std::vector<Coral>& corals);
int pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons(int argc, char* args[]);
void cleanup();
void updateFishRange(std::vector<Fish>& school, int start, int end, int id){
std::cout << "Thread updateFishRange ID : " << id << " : started" << std::endl;
int updateCount = 0;
while (running) {
std::this_thread::sleep_for(std::chrono::milliseconds(16));
//std::lock_guard<std::mutex> lock(mtx);
//std::cout << "Thread updateFishRange ID : " << id << " : update " << updateCount << " started" << std::endl;
for (int i = start; i < end; ++i) {
school[i].cycle();
void renderScene(std::vector<Player>& players, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks, const std::vector<Coral>& corals,Shark& shark );
void cleanup();
void closeGame();
void displayFPS(SDL_Renderer* renderer, TTF_Font* font, int fps);
void displayPlayerCoord(SDL_Renderer* renderer, TTF_Font* font, int playerX, int playerY);
void displayUnifiedPlayerCoord(SDL_Renderer* renderer, TTF_Font* font, int unifiedX, int unifiedY);
void displayPlayerCount(SDL_Renderer* renderer, TTF_Font* font, int playerCount);
void playerMovementThread(Player& player);
void handleClientMessages(Player& player);
void handleQuitThread();
void HandleMenuClick(Menu& menu);
void updateFishRange(std::vector<Fish>& school, int start, int end);
int pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons(int argc, char* args[]);
int pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons_mais_celle_ci_elle_lance_en_multijoueur(int argc, std::string args);
void checkThreads();
template <typename Function, typename... Args>
std::thread createThread(std::string key, Function&& func, Args&&... args) {
try {
std::cout << "Creating thread: " << key << std::endl;
std::thread thread([key, func = std::forward<Function>(func), ...args = std::forward<Args>(args)]() mutable {
ThreadInfo info;
info.id = std::this_thread::get_id();
info.functionName = key;
info.isRunning = true;
{
std::lock_guard<std::mutex> lock(mtx);
threadInfos.push_back(info);
}
try {
func(std::forward<Args>(args)...);
} catch (const std::exception& e) {
std::cerr << "Exception in thread " << key << ": " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception in thread " << key << std::endl;
}
{
std::lock_guard<std::mutex> lock(mtx);
for (auto& threadInfo : threadInfos) {
if (threadInfo.id == std::this_thread::get_id()) {
threadInfo.isRunning = false;
break;
}
}
}
std::cout << "ThreadID = " << info.id << " ThreadFunction = " << info.functionName << " finished" << std::endl;
});
return thread;
} catch (const std::system_error& e) {
std::cerr << "Failed to create thread: " << e.what() << std::endl;
throw;
}
}
void checkThreads() {
std::lock_guard<std::mutex> lock(mtx);
for (const auto& threadInfo : threadInfos) {
if (threadInfo.isRunning) {
std::cout << "Thread " << threadInfo.functionName << " (ID: " << threadInfo.id << ") is still running." << std::endl;
} else {
std::cout << "Thread " << threadInfo.functionName << " (ID: " << threadInfo.id << ") has stopped." << std::endl;
}
//std::cout << "Thread updateFishRange ID : " << id << " : update " << updateCount << " ended" << std::endl;
updateCount++;
}
}
void displayFPS(SDL_Renderer* renderer, TTF_Font* font, int fps) {
std::string fpsText = "FPS: " + std::to_string(fps);
SDL_Color color = {0, 255, 0}; // Vert
SDL_Color color = {0, 255, 0}; // Green
SDL_Surface* textSurface = TTF_RenderText_Solid(font, fpsText.c_str(), color);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_Rect textRect = {windowWidth - textSurface->w - 10, 10, textSurface->w, textSurface->h};
@@ -79,11 +149,41 @@ void displayPlayerCoord(SDL_Renderer* renderer, TTF_Font* font, int playerX, int
SDL_DestroyTexture(textTexture2);
}
void displayUnifiedPlayerCoord(SDL_Renderer* renderer, TTF_Font* font, int unifiedX, int unifiedY) {
std::string coordText = "Unified: (" + std::to_string(unifiedX) + ", " + std::to_string(unifiedY) + ")";
SDL_Color textColor = {0, 255, 0};
SDL_Surface* textSurface = TTF_RenderText_Solid(font, coordText.c_str(), textColor);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_Rect textRect = {10, 70, textSurface->w, textSurface->h};
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
SDL_FreeSurface(textSurface);
SDL_DestroyTexture(textTexture);
}
void displayPlayerCount(SDL_Renderer* renderer, TTF_Font* font, int playerCount) {
std::string playerCountText = "Player count: " + std::to_string(playerCount);
SDL_Color color = {0, 255, 0}; // Green
SDL_Surface* textSurface = TTF_RenderText_Solid(font, playerCountText.c_str(), color);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_Rect textRect = {windowWidth - textSurface->w - 10, 30, textSurface->w, textSurface->h};
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
SDL_FreeSurface(textSurface);
SDL_DestroyTexture(textTexture);
}
bool initSDL() {
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
return false;
}
if (SDLNet_Init() < 0) {
std::cerr << "SDLNet could not initialize! SDLNet_Error: " << SDLNet_GetError() << std::endl;
return false;
}
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0) {
std::cerr << "SDL_mixer could not initialize! SDL_mixer Error: " << Mix_GetError() << std::endl;
return false;
}
window = SDL_CreateWindow("BloubBloub les poissons",
SDL_WINDOWPOS_CENTERED,
@@ -145,17 +245,29 @@ bool initSDL() {
}
void playerMovementThread(Player& player) {
std::cout << "starting playerMovementThread..." << std::endl;
while (running) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
player.handlePlayerMovement(ENV_WIDTH, ENV_HEIGHT, windowWidth, windowHeight);
try {
std::cout << "Starting playerMovementThread for player " << player.getPlayerId() << std::endl;
while (game_running) {
player.handlePlayerMovement(ENV_WIDTH, ENV_HEIGHT, windowWidth, windowHeight);
std::this_thread::sleep_for(std::chrono::milliseconds(16)); // 60 FPS
}
std::cout << "Exiting playerMovementThread for player " << player.getPlayerId() << std::endl;
} catch (const std::exception& e) {
std::cerr << "Exception in playerMovementThread: " << e.what() << std::endl;
}
std::cout << "playerMovementThread ended" << std::endl;
}
void handleClientMessages(Player& player) {
std::cout << "messageThread started..." << std::endl;
while (messageThreadRunning) {
player.handleClientMessages();
}
std::cout << "messageThread ended" << std::endl;
}
void handleQuitThread() {
std::cout << "handleQuitThread..." << std::endl;
while (running) {
while (game_running) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
handleQuit();
}
@@ -163,24 +275,41 @@ void handleQuitThread() {
};
void HandleMenuClick(Menu& menu){
while (running) {
menu.handleClickedButton();
try {
while (menuRunning) {
menu.handleClickedButton();
}
} catch (const std::exception& e) {
std::cerr << "Exception in HandleMenuClick: " << e.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception in HandleMenuClick" << std::endl;
}
}
void fishMovementThread(std::vector<Fish>& school) {
std::cout << "starting fishMovementThread..." << std::endl;
while (running) {
void updateFishRange(std::vector<Fish>& school, int start, int end){
while (game_running) {
std::this_thread::sleep_for(std::chrono::milliseconds(16));
for (int i = 0; i < school.size(); ++i) {
school[i].cycle();
{
std::lock_guard<std::mutex> lock(mtx);
Fish::insertionSort(school);
}
for (int i = start; i < end; ++i) {
school[i].cycle(i);
}
}
std::cout << "fishMovementThread ended" << std::endl;
}
void updateShark(Shark &shark) {
while (game_running) {
std::this_thread::sleep_for(std::chrono::milliseconds(16));
shark.cycle();
}
}
int main(int argc, char* args[]) {
SDL_SetHint(SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR, "0");
int main(int argc, char* args[]){
if (!initSDL()) {
std::cerr << "Failed to initialize!" << std::endl;
return -1;
@@ -189,16 +318,15 @@ int main(int argc, char* args[]){
Menu menu(renderer);
menu.addPage("Main");
menu.addPage("Multi");
menu.addPage("Multi-Host");
menu.addPage("Multi-Join");
menu.changePage("Main");
std::thread menu_thread(HandleMenuClick, std::ref(menu));
std::thread menu_thread = createThread("Menu thread", HandleMenuClick, std::ref(menu));
std::thread quit_thread = createThread("Quit thread", handleQuitThread);
menu.addText("Main", (windowWidth/2) - 300, 50, 600, 100, "BloubBloub les poissons", 1024);
menu.addText("Multi-Host", (windowWidth/2) - 100, 50, 200, 100, "Host", 1024);
// Show current host IP
menu.addText("Multi-Host", (windowWidth/2) - 75, 200, 150, 50, "Host IP: 192.168.1.1", 1024);
menu.addText("Multi-Join", (windowWidth/2) - 100, 50, 200, 100, "Join", 1024);
menu.addButton("Main", (windowWidth/2) - 100, windowHeight/2 - 25, 200, 50, "Solo", 1024, [](){
std::cout << "SOlo" << std::endl;
@@ -207,40 +335,69 @@ int main(int argc, char* args[]){
});
menu.addButton("Main", (windowWidth/2) - 100, (windowHeight/2 + 75) - 25, 200, 50, "Multi", 1024, [&menu](){
menu.addButton("Main", (windowWidth/2) - 100, (windowHeight/2 + 75) - 25, 200, 50, "Multi (WIP)", 1024, [&menu](){
std::cout << "Multi" << std::endl;
menu.changePage("Multi");
});
menu.addButton("Multi", (windowWidth/2) - 100, windowHeight/2 - 25, 200, 50, "Host", 1024, [&menu](){
menu.changePage("Multi-Host");
std::cout << "Host" << std::endl;
isPlayingOnline = true;
menuRunning = false;
pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons_mais_celle_ci_elle_lance_en_multijoueur(0, "");
});
menu.addButton("Multi", (windowWidth/2) - 100, (windowHeight/2 + 75) - 25, 200, 50, "Join", 1024, [&menu](){
std::cout << "Join" << std::endl;
menu.changePage("Multi-Join");
});
// menu.addButton("Multi", (windowWidth/2) - 100, windowHeight/2 - 25, 200, 50, "Retour", 1024, [&menu](){
// menu.changePage("Main");
// });
menu.addButton("Multi-Host", (windowWidth/2) - 100, windowHeight/2 - 25, 200, 50, "", 24, [](){
std::cout << "Text input button clicked" << std::endl;
menu.addButton("Multi-Join", (windowWidth/2) - 100, windowHeight/2 - 25, 200, 50, "", 24, [](){
std::cout << "IP input button clicked" << std::endl;
}, true);
menu.addButton("Multi-Host", (windowWidth/2) - 100, (windowHeight/2 + 75) - 25, 200, 50, "", 24, [](){
std::cout << "Text input button clicked" << std::endl;
}, true);
menu.addButton("Multi-Join", (windowWidth/2) - 100, (windowHeight/2 + 75) - 25, 200, 50, "Join !", 1024, [&menu](){
std::cout << "Join" << std::endl;
isPlayingOnline = true;
menuRunning = false;
int port = 1234;
//char* ip = "10.30.42.206";
// Pour l'ip récupère l'interieur du bouton IP input
std::vector<Button> buttons = menu.getButtons();
std::string ip = buttons[0].inputText;
std::cout << ip << std::endl;
pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons_mais_celle_ci_elle_lance_en_multijoueur(port, ip);
});
menu.addButton("Multi-Host", (windowWidth/2) - 100, windowHeight/2 + 125, 200, 50, "Retour", 1024, [&menu](){
menu.addButton("Multi-Join", (windowWidth/2) - 100, windowHeight/2 + 125, 200, 50, "Retour", 1024, [&menu](){
menu.changePage("Multi");
});
menu.addButton("Multi", (windowWidth/2) - 100, windowHeight/2 + 125, 200, 50, "Retour", 1024, [&menu](){
menu.changePage("Main");
});
if (argc > 1 && std::string(args[1]) == "69") {
std::cout << "69" << std::endl;
pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons(0, nullptr);
}else if (argc > 1 && std::string(args[1]) == "420") {
std::cout << "420" << std::endl;
std::thread timer_thread([](){
std::this_thread::sleep_for(std::chrono::seconds(10));
game_running = false;
});
pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons(0, nullptr);
timer_thread.join();
}else if (argc > 1 && std::string(args[1]) == "80085") {
isPlayingOnline = true;
menuRunning = false;
pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons_mais_celle_ci_elle_lance_en_multijoueur(0, "");
}
//menu.addButton((windowWidth/2) - 100, (windowHeight/2 + 25) + 50, 200, 50, "Multi", 1024);
//std::thread quit_thread(handleQuitThread);
while (running) {
@@ -250,18 +407,34 @@ int main(int argc, char* args[]){
menu.draw(renderer);
}
}
SDL_Delay(10);
}
std::cout << "Check Threads 1" << std::endl;
checkThreads();
try {
if (menu_thread.joinable())
menuRunning = false;
if (menu_thread.joinable()) {
menuRunning = false;
menu_thread.join();
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
cleanup();
checkThreads();
try{
if(quit_thread.joinable())
quit_thread.join();
}catch(const std::system_error& e){
std::cerr << "Exception caught 2: " << e.what() << std::endl;
}
if (!isPlayingOnline) {
cleanup();
}
std::cout << "Check Threads 2" << std::endl;
checkThreads();
//pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons(argc, args);
return 0;
}
@@ -273,12 +446,83 @@ int pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mai
// return -1;
// }
game_running = true;
std::vector<Kelp> kelps;
std::vector<Rock> rocks;
std::vector<Coral> corals;
generateProceduralDecorations(kelps, rocks, corals,ENV_HEIGHT, ENV_WIDTH, renderer);
generateProceduralDecorations(kelps, rocks, corals, ENV_HEIGHT, ENV_WIDTH, renderer);
freopen("CON", "w", stdout);
freopen("CON", "w", stderr);
for (int i = 0; i < FISH_NUMBER ; ++i) {
school.emplace_back(rand() % ENV_WIDTH, rand() % ENV_HEIGHT, 0.1, 0.1, school, i, 75, 75, renderer, rand() % 2 == 0 ? 1 : 0, fishTextures[rand() % fishCount]);
}
std::ranges::sort(school, Fish::SortByX);
std::vector<std::thread> fish_threads;
int fishPerThread = school.size() / std::thread::hardware_concurrency();
for (int i = 0; i < school.size(); i += fishPerThread) {
fish_threads.emplace_back(createThread("Fish thread", updateFishRange, std::ref(school), i, std::min(i + fishPerThread, static_cast<int>(school.size()))));
}
//std::thread quit_thread = createThread("Quit thread", handleQuitThread);
// Offline
players.emplace_back(Player(windowWidth / 2, windowHeight / 2, 5, renderer, 0));
std::thread player_thread = createThread("Player thread", playerMovementThread, std::ref(players[0]));
Shark shark(0, 0, 0.1, 0.1,0, 150, 150, renderer,players);
std::thread shark_thread = createThread("Shark thread",updateShark, std::ref(shark));
while (game_running) {
renderScene(players, kelps, rocks, corals, shark);
//handleQuit();
}
try{
if(player_thread.joinable()){
std::cout << "Killing playerThread.." << std::endl;
player_thread.join();
}
}catch(const std::system_error& e){
std::cerr << "Exception caught 1: " << e.what() << std::endl;
}
try {
std::cout << "Killing fish_threads..." << std::endl;
for (auto& fish_thread : fish_threads) {
if (fish_thread.joinable())
fish_thread.join();
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught 4: " << e.what() << std::endl;
}
try {
if (shark_thread.joinable()){
std::cout << "Killing shark_thread..." << std::endl;
shark_thread.join();
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught 5: " << e.what() << std::endl;
}
std::cout << "All threads killed" << std::endl;
running = false;
return 0;
}
int pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mais_une_des_fonctions_principale_meme_primordiale_du_projet_denomme_bloubloulespoissons_mais_celle_ci_elle_lance_en_multijoueur(int argc, std::string args) {
// if (!initSDL()) {
// std::cerr << "Failed to initialize!" << std::endl;
// return -1;
// }
game_running = true;
std::vector<Kelp> kelps;
std::vector<Rock> rocks;
std::vector<Coral> corals;
generateProceduralDecorations(kelps, rocks, corals, ENV_HEIGHT, ENV_WIDTH, renderer);
for (int i = 0; i < FISH_NUMBER; ++i) {
school.emplace_back(Fish(rand() % ENV_WIDTH, rand() % ENV_HEIGHT, 0.1, 0.1, school, i, 75, 75, renderer, rand() % 2 == 0 ? 1 : 0, fishTextures[rand() % fishCount]));
}
std::cout << "Thread: " << std::thread::hardware_concurrency() << std::endl;
@@ -286,75 +530,186 @@ int pas_la_fontion_main_enfin_ce_nest_pas_la_fontion_principale_du_programme_mai
int fishPerThread = school.size() / std::thread::hardware_concurrency();
int thread_id = 0;
for (int i = 0; i < school.size(); i += fishPerThread) {
threads.emplace_back(updateFishRange, std::ref(school), i, std::min(i + fishPerThread, static_cast<int>(school.size())), thread_id);
thread_id++;
threads.emplace_back(createThread("Fish thread", updateFishRange, std::ref(school), i, std::min(i + fishPerThread, static_cast<int>(school.size()))));
}
Shark shark(0, 0, 0.1, 0.1,0, 150, 150, renderer,players);
std::thread shark_thread = createThread("Shark", updateShark, std::ref(shark));
freopen("CON", "w", stdout);
freopen("CON", "w", stderr);
Player player = Player(windowWidth / 2, windowHeight / 2, 5, renderer);
if (isPlayingOnline) {
if (argc == 0 && args == "") {
if (!initServer()) {
std::cerr << "Failed to initialize server!" << std::endl;
return -1;
}
isHost = true;
std::cout << "isHost: " << isHost << std::endl;
std::thread acceptThread = createThread("Accept thread", acceptClients);
IPaddress ip;
if (!initClient(ip, "localhost", 1234)) {
std::cerr << "Failed to initialize client!" << std::endl;
return -1;
}
players.emplace_back(Player(windowWidth / 2, windowHeight / 2, 5, renderer, 0));
std::ranges::sort(school, Fish::SortByX);
std::vector<std::thread> fish_threads;
int fishPerThread = school.size() / std::thread::hardware_concurrency();
for (int i = 0; i < school.size(); i += fishPerThread) {
fish_threads.emplace_back(createThread("Fish thread", updateFishRange, std::ref(school), i, std::min(i + fishPerThread, static_cast<int>(school.size()))));
}
messageThreadRunning = true;
std::thread messageThread = createThread("Message thread", handleClientMessages, std::ref(players[0]));
std::thread playerThread = createThread("Player thread", playerMovementThread, std::ref(players[0]));
std::thread player_thread(playerMovementThread, std::ref(player));
while (game_running) {
renderScene(players, kelps, rocks, corals,shark);
SDL_Delay(10);
}
messageThreadRunning = false;
try{
//if(playerThread.joinable())
std::cout << "Killing playerThread.." << std::endl;
playerThread.join();
std::cout << "playerThread killed" << std::endl;
std::thread quit_thread(handleQuitThread);
std::thread fish_thread(fishMovementThread, std::ref(school));
}catch(const std::system_error& e){
std::cerr << "Exception caught 1: " << e.what() << std::endl;
}
try {
for (auto& fish_thread : fish_threads) {
if (fish_thread.joinable())
fish_thread.join();
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught 2: " << e.what() << std::endl;
}
for (auto& thread : threads) {
try {
std::cout << "Killing thread..." << std::endl;
thread.join();
std::cout << "Thread killed" << std::endl;
} catch (const std::system_error& e) {
std::cerr << "Exception caught 3: " << e.what() << std::endl;
}
}
try {
//if (messageThread.joinable())
closeClient();
std::cout << "Killing messageThread" << std::endl;
messageThread.join();
std::cout << "messageThread killed" << std::endl;
} catch (const std::system_error& e) {
std::cerr << "Exception caught 4: " << e.what() << std::endl;
}
try {
if (acceptThread.joinable()){
std::cout << "Killing acceptThread" << std::endl;
acceptThread.join();
std::cout << "acceptThread killed" << std::endl;
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught 5: " << e.what() << std::endl;
}
while (running) {
renderScene(player, kelps, rocks, corals);
SDL_Delay(10);
}
running = false;
try{
if(player_thread.joinable())
player_thread.join();
}catch(const std::system_error& e){
std::cerr << "Exception caught: " << e.what() << std::endl;
}
try{
if(quit_thread.joinable())
quit_thread.join();
}catch(const std::system_error& e){
std::cerr << "Exception caught: " << e.what() << std::endl;
}
try {
if (fish_thread.joinable())
fish_thread.join();
} catch (const std::system_error& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
try {
for (auto& thread : threads) {
thread.join();
running = false;
}
else if (argc > 0 && argc < 65535 && args != "") {
int port = 1234;
std::string host = args;
if (!initClient(ip, host.c_str(), 1234)) {
std::cerr << "Failed to initialize client!" << std::endl;
return -1;
}
players.emplace_back(Player(windowWidth / 2, windowHeight / 2, 5, renderer, 1));
std::ranges::sort(school, Fish::SortByX);
std::vector<std::thread> fish_threads;
int fishPerThread = school.size() / std::thread::hardware_concurrency();
for (int i = 0; i < school.size(); i += fishPerThread) {
fish_threads.emplace_back(createThread("Fish thread", updateFishRange, std::ref(school), i, std::min(i + fishPerThread, static_cast<int>(school.size()))));
}
messageThreadRunning = true;
std::thread messageThread = createThread("Message thread", handleClientMessages, std::ref(players[0]));
std::thread playerThread = createThread("Player thread", playerMovementThread, std::ref(players[0]));
while (running) {
renderScene(players, kelps, rocks, corals,shark);
SDL_Delay(10);
}
messageThreadRunning = false;
try{
//if(playerThread.joinable())
std::cout << "Killing playerThread.." << std::endl;
playerThread.join();
std::cout << "playerThread killed" << std::endl;
}catch(const std::system_error& e){
std::cerr << "Exception caught 1: " << e.what() << std::endl;
}
try {
for (auto& fish_thread : fish_threads) {
if (fish_thread.joinable())
fish_thread.join();
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught 2: " << e.what() << std::endl;
}
for (auto& thread : threads) {
try {
std::cout << "Killing thread..." << std::endl;
thread.join();
std::cout << "Thread killed" << std::endl;
} catch (const std::system_error& e) {
std::cerr << "Exception caught 3: " << e.what() << std::endl;
}
}
try {
//if (messageThread.joinable())
closeClient();
std::cout << "Killing messageThread" << std::endl;
messageThread.join();
std::cout << "messageThread killed" << std::endl;
} catch (const std::system_error& e) {
std::cerr << "Exception caught 4: " << e.what() << std::endl;
}
running = false;
}
} catch (const std::system_error& e) {
std::cerr << "Exception caught: " << e.what() << std::endl;
}
return 0;
}
void handleQuit() {
SDL_Event event;
const Uint8* keystate = SDL_GetKeyboardState(NULL);
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) {
running = false;
if (isPlayingOnline && isHost) {
closeServer();
}
game_running = false;
}
}
if (keystate[SDL_SCANCODE_ESCAPE]) {
running = false;
if (isPlayingOnline && isHost) {
closeServer();
}
game_running = false;
}
}
void renderScene(Player player, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks, const std::vector<Coral>& corals) {
void renderScene(std::vector<Player>& players, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks, const std::vector<Coral>& corals,Shark& shark) {
static Uint32 lastTime = 0;
static int frameCount = 0;
static int fps = 0;
//std::cout << "renderScene for " << players.size() << " players" << std::endl;
Uint32 currentTime = SDL_GetTicks();
const Uint32 currentTime = SDL_GetTicks64();
frameCount++;
if (currentTime - lastTime >= 1000) {
fps = frameCount;
@@ -381,33 +736,97 @@ void renderScene(Player player, const std::vector<Kelp>& kelps, const std::vecto
coral.draw(renderer);
}
std::lock_guard<std::mutex> lock(mtx);
for (Fish& fish : school) {
fish.draw(renderer);
}
player.draw(renderer);
for (auto& player : players) {
player.draw(renderer);
}
shark.draw(renderer);
displayFPS(renderer, font, fps);
auto [playerX, playerY] = player.getPlayerPos();
displayPlayerCoord(renderer, font, playerX, playerY);
SDL_RenderPresent(renderer);
}
void cleanup() {
TTF_CloseFont(font);
TTF_Quit();
SDL_DestroyTexture(backgroundTexture);
try {
if (font != nullptr) {
TTF_CloseFont(font);
font = nullptr;
}
} catch (const std::exception& e) {
std::cerr << "Exception caught for CloseFont: " << e.what() << std::endl;
}
try {
TTF_Quit();
} catch (const std::exception& e) {
std::cerr << "Exception caught for TTF_Quit: " << e.what() << std::endl;
}
try {
if (playerTexture != nullptr) {
SDL_DestroyTexture(playerTexture);
playerTexture = nullptr;
}
} catch (const std::exception& e) {
std::cerr << "Exception caught for DestroyTexture (playerTexture): " << e.what() << std::endl;
}
for (int i = 0; i < fishCount; ++i) {
SDL_DestroyTexture(fishTextures[i]);
try {
if (fishTextures[i] != nullptr) {
SDL_DestroyTexture(fishTextures[i]);
fishTextures[i] = nullptr;
}
} catch (const std::exception& e) {
std::cerr << "Exception caught for DestroyTexture (fishTextures[" << i << "]): " << e.what() << std::endl;
}
}
if (renderer != nullptr) {
SDL_DestroyRenderer(renderer);
try {
if (renderer != nullptr) {
SDL_DestroyRenderer(renderer);
renderer = nullptr;
}
} catch (const std::exception& e) {
std::cerr << "Exception caught for DestroyRenderer: " << e.what() << std::endl;
}
if (window != nullptr) {
SDL_DestroyWindow(window);
try {
if (window != nullptr) {
SDL_DestroyWindow(window);
window = nullptr;
}
} catch (const std::exception& e) {
std::cerr << "Exception caught for DestroyWindow: " << e.what() << std::endl;
}
try {
IMG_Quit();
} catch (const std::exception& e) {
std::cerr << "Exception caught for IMG_Quit: " << e.what() << std::endl;
}
try {
SDLNet_Quit();
} catch (const std::exception& e) {
std::cerr << "Exception caught for SDLNet_Quit: " << e.what() << std::endl;
}
try {
Mix_CloseAudio();
} catch (const std::exception& e) {
std::cerr << "Exception caught for Mix_CloseAudio: " << e.what() << std::endl;
}
try {
SDL_Quit();
} catch (const std::exception& e) {
std::cerr << "Exception caught for SDL_Quit: " << e.what() << std::endl;
}
IMG_Quit();
SDL_Quit();
}

View File

@@ -163,3 +163,8 @@ void Menu::addPage(std::string title){
page.title = title;
pages.push_back(page);
}
std::vector<Button> Menu::getButtons(){
return pages[currentPage].buttons;
}

2
menu.h
View File

@@ -75,6 +75,8 @@ class Menu {
void addText(std::string page, int x, int y, int w, int h, std::string text, int size);
void addPage(std::string title);
std::vector<Button> getButtons();
};
#endif

233
network/networking.cpp Normal file
View File

@@ -0,0 +1,233 @@
//
// Created by BreizhHardware on 04/12/2024.
//
#include "networking.h"
std::unordered_map<int, std::pair<int, int>> playerPositions;
std::unordered_map<int, std::chrono::time_point<std::chrono::steady_clock>> lastKeepAlive;
bool initServer() {
std::cout << "Initializing server..." << std::endl;
if (SDLNet_ResolveHost(&ip, NULL, 1234) == -1) {
std::cerr << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
return false;
}
server = SDLNet_TCP_Open(&ip);
if (!server) {
std::cerr << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
return false;
}
std::cout << "Server initialized!" << std::endl;
return true;
}
void acceptClients() {
while (game_running) {
TCPsocket clientSocket = SDLNet_TCP_Accept(server);
if (clientSocket) {
clients.push_back(clientSocket);
int clientId = clients.size() - 1;
createNewPlayer(clientId);
updateKeepAlive(clientId);
Shark shark(0, 0, 0.1, 0.1,0, 150, 150, renderer,players_server);
shark.updatePosition(0, 0);
std::thread clientThread([clientSocket, clientId, &shark]() {
std::thread keepAliveThread(sendKeepAlive, clientSocket);
keepAliveThread.detach();
while (running) {
std::string message = receiveMessage(clientSocket);
if (!message.empty()) {
message = processReceivedData(message);
std::cout << "Server received: " << message << std::endl;
if (message == "keepalive") {
updateKeepAlive(clientId);
} else if (message.find(";move;") != std::string::npos) {
char direction[20];
sscanf(message.c_str(), "%d;move;%s", &clientId, &direction);
int newX = 0, newY = 0;
std::tie(newX, newY) = updatePlayerPosition(clientId, direction);
// Mettre à jour la position du joueur
players_server[clientId].updatePosition(newX, newY);
std::string updatedMessage = std::to_string(clientId) + ";moved;" + std::to_string(newX) + "," + std::to_string(newY);
for (TCPsocket client : clients) {
sendMessage(client, updatedMessage);
}
} else if (message.find(";shark_moved;") != std::string::npos) {
int sharkId, x, y;
sscanf(message.c_str(), "%d;shark_moved;%d,%d", &sharkId, &x, &y);
shark.updatePosition(x, y);
std::string updatedMessage = std::to_string(sharkId) + ";shark_moved;" + std::to_string(x) + "," + std::to_string(y);
for (TCPsocket client : clients) {
sendMessage(client, updatedMessage);
}
}
}
SDL_Delay(1);
}
lastKeepAlive.erase(clientId);
SDLNet_TCP_Close(clientSocket);
});
clientThread.detach();
}
SDL_Delay(100);
}
}
std::vector<std::string> split(const std::string& str, char delimiter) {
std::vector<std::string> result;
std::string temp;
for (char ch : str) {
if (ch == delimiter) {
if (!temp.empty()) { // On évite d'ajouter des chaînes vides si nécessaire
result.push_back(temp);
}
temp.clear(); // Réinitialise pour le prochain segment
} else {
temp += ch;
}
}
if (!temp.empty()) { // Ajouter le dernier segment s'il existe
result.push_back(temp);
}
return result;
}
std::pair<int, int> updatePlayerPosition(int clientId, const std::string& direction) {
std::cout << "Updating player position for client " << clientId << " Direction: "<< direction << std::endl;
auto& pos = playerPositions[clientId];
int& newX = pos.first;
int& newY = pos.second;
int speed = 5;
std::vector<std::string> directions = split(direction, '-');
if(directions.size() > 1 ){
speed = 3;
}
for(const std::string dist : directions){
if (dist == "up") {
if (newY-speed < 0) {
newY = 0;
} else {
newY -= speed;
}
} else if (dist == "down") {
if (newY+speed > ENV_HEIGHT - windowHeight) {
newY = ENV_HEIGHT - windowHeight;
} else {
newY += speed;
}
} else if (dist == "left") {
if (newX-speed < 0) {
newX = 0;
} else {
newX -= speed;
}
} else if (dist == "right") {
if (newX+speed > ENV_WIDTH - windowWidth) {
newX = ENV_WIDTH - windowWidth;
} else {
newX += speed;
}
}
}
return {newX, newY};
}
void createNewPlayer(int clientId) {
if (clientId < 0) {
std::cerr << "Invalid client ID: " << clientId << std::endl;
return;
}
// Create a new player at a default position (e.g., 0, 0)
Player newPlayer(0, 0, 5, renderer, clientId);
players_server.push_back(newPlayer);
playerPositions[clientId] = {0, 0}; // Initialize player position
// Send the list of existing players to the new client
std::string playerListMessage = "playerList;";
for (auto& player : players_server) {
auto [x, y] = player.getPlayerPos();
playerListMessage += std::to_string(player.getPlayerId()) + "," + std::to_string(x) + "," + std::to_string(y) + ";";
}
sendMessage(clients[clientId], playerListMessage);
// Broadcast the new player to all clients
std::string newPlayerMessage = "newPlayer;" + std::to_string(clientId) + ",0,0;";
for (TCPsocket client : clients) {
sendMessage(client, newPlayerMessage);
}
}
void updateKeepAlive(int clientId) {
lastKeepAlive[clientId] = std::chrono::steady_clock::now();
}
void checkClientAlive() {
auto now = std::chrono::steady_clock::now();
for (auto it = lastKeepAlive.begin(); it != lastKeepAlive.end();) {
if (std::chrono::duration_cast<std::chrono::seconds>(now - it->second).count() > 5) {
std::cerr << "Client " << it->first << " is not responding. Removing..." << std::endl;
SDLNet_TCP_Close(clients[it->first]);
clients.erase(clients.begin() + it->first);
playerPositions.erase(it->first); // Supprimer la position du joueur
it = lastKeepAlive.erase(it);
} else {
++it;
}
}
}
void closeServer() {
std::string quitMessage = "host;quit";
for (TCPsocket client : clients) {
sendMessage(client, quitMessage);
}
// Fermer les sockets et nettoyer les ressources
for (TCPsocket client : clients) {
SDLNet_TCP_Close(client);
}
clients.clear();
SDLNet_TCP_Close(server);
}
void handleServerMessages() {
std::string message = receiveMessage(server);
if (!message.empty()) {
std::cout << "Server received: " << message << std::endl;
if (message.find(";moved;") != std::string::npos) {
int clientId, x, y;
sscanf(message.c_str(), "%d;moved;%d,%d", &clientId, &x, &y);
// Mettre à jour la position du joueur dans players_server
for (auto& player : players_server) {
std::cout << "Player ID: " << player.getPlayerId() << std::endl;
std::cout << "Client ID: " << clientId << std::endl;
std::cout << "PlayerId == ClientId: " << (player.getPlayerId() == clientId) << std::endl;
if (player.getPlayerId() == clientId) {
player.updatePosition(x, y);
std::cout << "Player " << clientId << " moved to " << player.getUnifiedX() << ", " << player.getUnifiedY() << std::endl;
break;
}
}
}
}
}
void sendSharkPosition(TCPsocket socket, int sharkId, int x, int y) {
std::string message = std::to_string(sharkId) + ";shark_moved;" + std::to_string(x) + "," + std::to_string(y);
sendMessage(socket, message);
}
std::string processReceivedData(const std::string& data) {
std::string filteredData;
for (char c : data) {
if (std::isalnum(c) || c == ';' || c == '-' || c == '_' || std::isalpha(c)) {
filteredData += c;
}
}
return filteredData;
}

30
network/networking.h Normal file
View File

@@ -0,0 +1,30 @@
#ifndef NETWORKING_H
#define NETWORKING_H
#include <SDL2/SDL_net.h>
#include <vector>
#include <iostream>
#include <thread>
#include <unordered_map>
#include <chrono>
#include "../env.h"
#include "networking_client.h"
#include "../player.h"
#include "../shark.h"
inline IPaddress ip;
inline TCPsocket server;
inline std::vector<TCPsocket> clients;
bool initServer();
void acceptClients();
std::pair<int, int> updatePlayerPosition(int clientId, const std::string& direction);
void createNewPlayer(int clientId);
void updateKeepAlive(int clientId);
void checkClientAlive();
void closeServer();
void handleServerMessages();
void sendSharkPosition(TCPsocket socket, int sharkId, int x, int y);
std::string processReceivedData(const std::string& data);
#endif //NETWORKING_H

View File

@@ -0,0 +1,145 @@
#include "networking_client.h"
extern TCPsocket server;
bool initClient(IPaddress& ip, const char* host, int port) {
std::cout << "Initializing client..." << std::endl;
if (SDLNet_ResolveHost(&ip, host, port) < 0) {
std::cerr << "SDLNet_ResolveHost: " << SDLNet_GetError() << std::endl;
return false;
}
client = SDLNet_TCP_Open(&ip);
if (!client) {
std::cerr << "SDLNet_TCP_Open: " << SDLNet_GetError() << std::endl;
return false;
}
std::cout << "Client initialized!" << std::endl;
return true;
}
void closeClient() {
try{
if(client)
SDLNet_TCP_Close(client);
}catch(const std::exception& e){
std::cerr << "Exception caught: " << e.what() << std::endl;
}
}
void sendMessage(TCPsocket socket, const std::string& message) {
if (!socket) {
std::cerr << "Invalid socket" << std::endl;
return;
}
int len = message.length();
int result = SDLNet_TCP_Send(socket, &len, sizeof(len));
if (result < sizeof(len)) {
std::cerr << "SDLNet_TCP_Send failed: " << SDLNet_GetError() << std::endl;
std::cerr << "Closing the game ..." << std::endl;
game_running = false;
return;
}
result = SDLNet_TCP_Send(socket, message.c_str(), len);
if (result < len) {
std::cerr << "SDLNet_TCP_Send failed: " << SDLNet_GetError() << std::endl;
}
}
std::string receiveMessage(TCPsocket socket) {
int len;
if (SDLNet_TCP_Recv(socket, &len, sizeof(len)) <= 0) {
//std::cerr << "Failed to receive message length" << std::endl;
return "";
}
if (len <= 0 || len > 10000) { // Ajustez cette valeur selon vos besoins
//std::cerr << "Invalid message length: " << len << std::endl;
return "";
}
char* buffer = new(std::nothrow) char[len + 1];
if (!buffer) {
//std::cerr << "Memory allocation failed" << std::endl;
return "";
}
if (SDLNet_TCP_Recv(socket, buffer, len) <= 0) {
//std::cerr << "Failed to receive message" << std::endl;
delete[] buffer;
return "";
}
buffer[len] = '\0';
std::string message(buffer);
delete[] buffer;
return message;
}
void handleClientMessage(Player& player) {
std::cout << "handleClientMessage called" << std::endl;
char message[1024];
while (messageThreadRunning) {
int len = SDLNet_TCP_Recv(server, message, 1024);
if (len > 0) {
message[len] = '\0';
std::string msg(message);
std::istringstream iss(msg);
std::string token;
while (std::getline(iss, token, ';')) {
std::cout << "Token: " << token << std::endl; // Ajout de débogage
if (token == "playerList") {
while (std::getline(iss, token, ';')) {
int playerId, x, y;
sscanf(token.c_str(), "%d,%d,%d", &playerId, &x, &y);
if (playerId > 0 && playerId < players.size()) {
players[playerId].updatePosition(x, y);
} else {
players.emplace_back(Player(x, y, 5, renderer, playerId));
}
}
} else if (token == "newPlayer") {
int playerId, x, y;
sscanf(token.c_str(), "%d,%d,%d", &playerId, &x, &y);
if (playerId > 0) {
players.emplace_back(Player(x, y, 5, renderer, playerId));
}
} else {
int playerId = std::stoi(token);
std::getline(iss, token, ';');
int unifiedX = std::stoi(token);
std::getline(iss, token, ';');
int unifiedY = std::stoi(token);
std::getline(iss, token, ';');
int PlayerX = std::stoi(token);
std::getline(iss, token, ';');
int PlayerY = std::stoi(token);
std::cout << "Unified position: " << unifiedX << ", " << unifiedY << std::endl;
if (playerId > 0 && playerId < players.size()) {
players[playerId].updatePosition(PlayerX, PlayerY);
}
}
}
}
}
}
void sendKeepAlive(TCPsocket serverSocket) {
while (game_running) {
std::string keepAliveMessage = "keepalive";
sendMessage(serverSocket, keepAliveMessage);
SDL_Delay(3000); // Envoyer un message de keepalive toutes les 3 secondes
}
}
void startKeepAlive(TCPsocket serverSocket) {
std::thread([serverSocket] () {
while (messageThreadRunning) {
sendKeepAlive(serverSocket);
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}).detach();
}

View File

@@ -0,0 +1,27 @@
//
// Created by BreizhHardware on 04/12/2024.
//
#ifndef NETWORKING_CLIENT_H
#define NETWORKING_CLIENT_H
#include <SDL2/SDL_net.h>
#include <iostream>
#include <sstream>
#include <thread>
#include <chrono>
#include "../env.h"
#include "../player.h"
class Player;
inline TCPsocket client;
bool initClient(IPaddress& ip, const char* host, int port);
void closeClient();
void sendMessage(TCPsocket socket, const std::string& message);
std::string receiveMessage(TCPsocket socket);
void handleClientMessage(Player& player);
void sendKeepAlive(TCPsocket serverSocket);
void startKeepAlive(TCPsocket serverSocket);
#endif //NETWORKING_CLIENT_H

View File

@@ -1,5 +1,8 @@
#include "player.h"
#include <syncstream>
#include <tuple>
#include "network/networking_client.h"
#include "camera.h"
void Player::updatePlayerPos(int x, int y) {
@@ -13,7 +16,7 @@ void Player::updatePlayerSpeed(int playerSpeed) {
this->playerSpeed = playerSpeed;
};
std::tuple<int, int> Player::getPlayerPos() {
std::tuple<int, int> Player::getPlayerPos() const {
return std::make_tuple(this->x, this->y);
};
@@ -46,12 +49,11 @@ void Player::draw(SDL_Renderer* renderer) {
SDL_RenderCopyEx(renderer, this->playerTexture, &this->playerRect[this->currentSprite], &this->playerPosForRender, 0, nullptr, this->currentFlip);
this->drawEnergyBar(renderer);
};
void Player::handlePlayerMovement(int ENV_WIDTH, int ENV_HEIGHT, int windowWidth, int windowHeight) {
SDL_Event event;
const Uint8* keystate = SDL_GetKeyboardState(NULL);
Camera& camera = Camera::getInstance();
int tempX = this->x;
@@ -64,57 +66,71 @@ void Player::handlePlayerMovement(int ENV_WIDTH, int ENV_HEIGHT, int windowWidth
}
bool moved = false;
if (this->energy != 0){
if (keystate[SDL_SCANCODE_W]) {
if (camera.getY() > 0 && tempY == this->playerBaseY) {
camera.move(0, -speed);
} else if (tempY > 0) {
tempY -= speed;
if (this->energy != 0) {
if (isPlayingOnline) {
if (keystate[SDL_SCANCODE_W] || keystate[SDL_SCANCODE_S] || keystate[SDL_SCANCODE_A] || keystate[SDL_SCANCODE_D]) {
moved = onlineMovement();
}
moved = true;
}
if (keystate[SDL_SCANCODE_S]) {
if ((camera.getY() < ENV_HEIGHT - windowHeight) && (tempY == this->playerBaseY)) {
camera.move(0, speed);
} else if (tempY < windowHeight - PLAYER_SIZE_Y) {
tempY += speed;
} else {
if (keystate[SDL_SCANCODE_W]) {
if (camera.getY() > 0 && tempY == this->playerBaseY) {
camera.move(0, -speed);
unifiedX = camera.getX() + this->x;
} else if (tempY > 0) {
tempY -= speed;
unifiedX = camera.getX() + this->x;
}
moved = true;
}
moved = true;
}
if (keystate[SDL_SCANCODE_A]) {
if (camera.getX() > 0 && (tempX == this->playerBaseX)) {
camera.move(-speed, 0);
this->currentFlip = SDL_FLIP_HORIZONTAL;
} else if (tempX > 0) {
tempX -= speed;
this->currentFlip = SDL_FLIP_HORIZONTAL;
if (keystate[SDL_SCANCODE_S]) {
if ((camera.getY() < ENV_HEIGHT - windowHeight) && (tempY == this->playerBaseY)) {
camera.move(0, speed);
unifiedX = camera.getX() + this->x;
} else if (tempY < windowHeight - PLAYER_SIZE_Y) {
tempY += speed;
unifiedX = camera.getX() + this->x;
}
moved = true;
}
moved = true;
}
if (keystate[SDL_SCANCODE_D]) {
if (camera.getX() < ENV_WIDTH - windowWidth && (tempX == this->playerBaseX)) {
camera.move(speed, 0);
this->currentFlip = SDL_FLIP_NONE;
} else if (tempX < windowWidth - PLAYER_SIZE_X) {
tempX += speed;
this->currentFlip = SDL_FLIP_NONE;
if (keystate[SDL_SCANCODE_A]) {
if (camera.getX() > 0 && (tempX == this->playerBaseX)) {
camera.move(-speed, 0);
this->currentFlip = SDL_FLIP_HORIZONTAL;
unifiedY = camera.getY() + this->y;
} else if (tempX > 0) {
tempX -= speed;
this->currentFlip = SDL_FLIP_HORIZONTAL;
unifiedY = camera.getY() + this->y;
}
moved = true;
}
if (keystate[SDL_SCANCODE_D]) {
if (camera.getX() < ENV_WIDTH - windowWidth && (tempX == this->playerBaseX)) {
camera.move(speed, 0);
this->currentFlip = SDL_FLIP_NONE;
unifiedY = camera.getY() + this->y;
} else if (tempX < windowWidth - PLAYER_SIZE_X) {
tempX += speed;
this->currentFlip = SDL_FLIP_NONE;
unifiedY = camera.getY() + this->y;
}
moved = true;
}
moved = true;
}
if (tempX < 0) {
tempX = 0;
} else if (tempX > ENV_WIDTH) {
tempX = ENV_WIDTH;
}
if (tempX < 0) {
tempX = 0;
} else if (tempX > ENV_WIDTH) {
tempX = ENV_WIDTH;
}
if (tempY < 0) {
tempY = 0;
} else if (tempY > ENV_HEIGHT) {
tempY = ENV_HEIGHT;
}
if (tempY < 0) {
tempY = 0;
} else if (tempY > ENV_HEIGHT) {
tempY = ENV_HEIGHT;
}
this->updatePlayerPos(tempX, tempY);
this->updatePlayerPos(tempX, tempY);
}
}
if (moved) {
lastMoveTime = SDL_GetTicks();
@@ -126,14 +142,22 @@ void Player::handlePlayerMovement(int ENV_WIDTH, int ENV_HEIGHT, int windowWidth
if (this->energy < 0) {
this->energy = 0;
}
unifiedX = camera.getX() + this->x;
unifiedY = camera.getY() + this->y;
} else {
Uint32 currentTime = SDL_GetTicks();
if (currentTime - lastMoveTime >= 5000) {
this->energy += 0.2f;
if (currentTime - lastMoveTime >= 1000) {
if (this->energy > 50.0f) {
this->energy += 0.4f; // Récupération plus rapide si l'énergie est élevée
} else {
this->energy += 0.2f; // Récupération plus lente si l'énergie est faible
}
if (this->energy > 100.0f) {
this->energy = 100.0f;
}
}
unifiedX = camera.getX() + this->x;
unifiedY = camera.getY() + this->y;
}
}
@@ -146,4 +170,87 @@ void Player::drawEnergyBar(SDL_Renderer* renderer) {
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
SDL_RenderFillRect(renderer, &energyBarForeground);
}
}
int Player::getPlayerId() {
return playerId;
}
void Player::setPlayerPos(int x, int y) {
this->x = x;
this->y = y;
this->playerPosForRender.x = x;
this->playerPosForRender.y = y;
}
void Player::handleClientMessages() {
std::string message = receiveMessage(client);
if (!message.empty()) {
std::cout << "Client received: " << message << std::endl;
if (message == "host;quit") {
std::cout << "Host has quit. Closing client..." << std::endl;
game_running = false;
return;
}
if (message.find(";moved;") != std::string::npos) {
int clientId, xCam, yCam;
sscanf(message.c_str(), "%d;moved;%d,%d", &clientId, &xCam, &yCam);
if (clientId == playerId) {
this->setPlayerPos(750, 400);
Camera& camera = Camera::getInstance();
if (xCam >= 0 && xCam <= ENV_WIDTH - windowWidth) {
if ( yCam >= 0 && yCam <= ENV_HEIGHT - windowHeight) {
camera.setPosition(xCam, yCam);
updatePosition(xCam, yCam);
}
}
}
}
}
}
bool Player::onlineMovement() {
const Uint8* keystate = SDL_GetKeyboardState(NULL);
std::string message = std::to_string(getPlayerId()) + ";move;";
bool moved = false;
if (keystate[SDL_SCANCODE_W]) {
message += "up-";
moved = true;
}
if (keystate[SDL_SCANCODE_S]) {
message += "down-";
moved = true;
}
if (keystate[SDL_SCANCODE_A]) {
message += "left-";
moved = true;
}
if (keystate[SDL_SCANCODE_D]) {
message += "right-";
moved = true;
}
if (moved) {
sendMessage(client, message);
return true;
}
return false;
}
void Player::updatePosition(int x, int y) {
int camX = x + windowWidth / 2;
int camY = y + windowHeight / 2;
unifiedX = camX;
unifiedY = camY;
}
int Player::getUnifiedX() {
return unifiedX;
}
int Player::getUnifiedY() {
return unifiedY;
}
int Player::getSpeed() {
return playerSpeed;
}

View File

@@ -27,6 +27,7 @@ class Player {
int playerSpeed;
int currentSprite = PLAYER_SPRITE_1;
int ticks = 0;
int playerId;
float energy = 100.0f;
SDL_RendererFlip currentFlip = SDL_FLIP_NONE;
SDL_Texture* playerTexture = nullptr;
@@ -36,11 +37,17 @@ class Player {
{326, 73, 112, 117},
{528, 73, 112, 117}
};
Uint32 lastMoveTime;
Uint32 lastMoveTime;
bool onlineMovement();
int unifiedX = 0;
int unifiedY = 0;
int HITBOX = 50;
public:
Player(int x, int y, int playerSpeed, SDL_Renderer* renderer) : x(x), y(y), playerBaseX(x), playerBaseY(y), playerSpeed(playerSpeed) {
Player(int x, int y, int playerSpeed, SDL_Renderer* renderer, int playerId) : x(x), y(y), playerBaseX(x), playerBaseY(y), playerSpeed(playerSpeed), playerId(playerId) {
playerPosForRender.x = x;
playerPosForRender.y = y;
unifiedX = x + windowWidth / 2;
unifiedY = y + windowHeight / 2;
SDL_Surface* playerSurface = IMG_Load(playerIMG);
if (playerSurface == nullptr) {
@@ -53,12 +60,26 @@ class Player {
};
void updatePlayerPos(int x, int y);
void updatePlayerSpeed(int playerSpeed);
std::tuple<int, int> getPlayerPos();
std::tuple<int, int> getPlayerPos() const;
int getPlayerSpeed();
void draw(SDL_Renderer* renderer);
void handlePlayerMovement(int ENV_WIDTH, int ENV_HEIGHT, int windowWidth, int windowHeight);
void drawEnergyBar(SDL_Renderer* renderer);
bool checkCollision(SDL_Rect fishRect);
int getPlayerId();
void setPlayerPos(int x, int y);
void handleClientMessages();
void updatePosition(int x, int y);
int getUnifiedX();
int getUnifiedY();
int getSpeed();
SDL_Texture* getTexture() {
return playerTexture;
}
int getHITBOX() const {return HITBOX;}
};
#endif

125
shark.cpp Normal file
View File

@@ -0,0 +1,125 @@
//
// Created by cfouche on 09/12/24.
//
#define sharkIMG "../img/shark.png"
#include "shark.h"
#include "network/networking.h"
Shark::Shark(const int x, const int y, const float vx, const float vy, const int id, const int width, const int height, SDL_Renderer* renderer, std::vector<Player> &players_list)
: x(x), y(y), vx(vx), vy(vy), id(id), width(width), height(height), players_list(players_list) {
SDL_Surface* sharkSurface = IMG_Load(sharkIMG);
if (sharkSurface == nullptr) {
std::cerr << "Erreur de chargement de l'image du joueur: " << IMG_GetError() << std::endl;
} else {
texture = SDL_CreateTextureFromSurface(renderer, sharkSurface);
SDL_FreeSurface(sharkSurface);
}
sharkSound = Mix_LoadWAV("../sounds/shark.wav");
if (sharkSound == nullptr) {
std::cerr << "Erreur de chargement du son du requin: " << Mix_GetError() << std::endl;
}
lastSoundTime = std::chrono::steady_clock::now();
}
void Shark::draw(SDL_Renderer *renderer) {
Camera &camera = Camera::getInstance();
int cameraX = camera.getX();
int cameraY = camera.getY();
SDL_Rect rect = {static_cast<int>(x) - cameraX, static_cast<int>(y) - cameraY, width, height};
float angle = atan2(vy, vx) * 180 / M_PI; // Convert angle to degrees
if (texture) {
SDL_RenderCopyEx(renderer, texture, nullptr, &rect, angle, nullptr, SDL_FLIP_NONE);
} else {
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); // Green
SDL_RenderFillRect(renderer, &rect);
}
}
bool Shark::isInView(Player& player) {
return player.getUnifiedX() >= x - VISUAL_RANGE && player.getUnifiedX() <= x + VISUAL_RANGE && player.getUnifiedY() >= y - VISUAL_RANGE && player.getUnifiedY() <= y + VISUAL_RANGE;
}
void Shark::checkNeighborhood(Player& player, float &xpos_avg, float &ypos_avg, float &xvel_avg, float &yvel_avg, int &neighboring_player) {
if (isInView(player)) {
xpos_avg += player.getUnifiedX();
ypos_avg += player.getUnifiedY();
xvel_avg += player.getSpeed();
yvel_avg += player.getSpeed();
neighboring_player++;
}
}
void Shark::checkCollision(Player& player) {
if (player.getUnifiedX() + player.getHITBOX() >= x - HITBOX && player.getUnifiedX() - player.getHITBOX() <= x + HITBOX && player.getUnifiedY() + player.getHITBOX() >= y - HITBOX && player.getUnifiedY() - player.getHITBOX() <= y + HITBOX) {
game_running = false;
}
}
void Shark::cycle() {
int neighboring_player = 0;
float xvel_avg = 0, yvel_avg = 0, xpos_avg = 0, ypos_avg = 0;
for (auto& player : players_list) {
if (isInView(player)) {
checkNeighborhood(player, xpos_avg, ypos_avg, xvel_avg, yvel_avg, neighboring_player);
checkCollision(player);
}
}
if (neighboring_player > 0) {
xpos_avg /= neighboring_player;
ypos_avg /= neighboring_player;
xvel_avg /= neighboring_player;
yvel_avg /= neighboring_player;
vx += (xpos_avg - x) * CENTERING_FACTOR + (xvel_avg - vx) * MATCHING_FACTOR;
vy += (ypos_avg - y) * CENTERING_FACTOR + (yvel_avg - vy) * MATCHING_FACTOR;
}
float speed = sqrt(vx * vx + vy * vy);
if (speed > MAX_SPEED) {
vx = vx / speed * MAX_SPEED;
vy = vy / speed * MAX_SPEED;
} else if (speed < MIN_SPEED) {
vx = vx / speed * MIN_SPEED;
vy = vy / speed * MIN_SPEED;
}
x += vx;
y += vy;
auto now = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<std::chrono::seconds>(now - lastSoundTime).count() > 15) {
if (sharkSound != nullptr) {
Mix_PlayChannel(-1, sharkSound, 0);
}
lastSoundTime = now;
}
if (isPlayingOnline && isHost) {
if (std::chrono::duration_cast<std::chrono::milliseconds>(now - lastSendTime).count() >= 100) {
sendSharkPosition(client, id, x, y);
lastSendTime = now;
}
}
}
Shark::~Shark() {
if (texture) {
SDL_DestroyTexture(texture);
texture = nullptr;
}
if (sharkSound) {
Mix_FreeChunk(sharkSound);
sharkSound = nullptr;
}
}
void Shark::updatePosition(int newX, int newY) {
x = newX;
y = newY;
}

61
shark.h Normal file
View File

@@ -0,0 +1,61 @@
//
// Created by cfouche on 09/12/24.
//
#ifndef SHARK_H
#define SHARK_H
#include <vector>
#include "player.h"
#include <SDL2/SDL.h>
#include <SDL2/SDL_mixer.h>
#include <chrono>
class Shark {
private:
const int VISUAL_RANGE = 500;
const float AVOIDANCE_FORCE = 0.05;
const float MATCHING_FACTOR = 0.05;
const float CENTERING_FACTOR = 0.005;
const float TURN_FACTOR = 0.3;
const float MAX_SPEED = 3;
const float MIN_SPEED = 0.6;
const float BIASVALUE = 0.001;
const int HITBOX = 50;
float x, y;
float vx, vy;
int id;
SDL_Texture* texture;
int width, height;
std::vector<Player> &players_list;
Mix_Chunk* sharkSound;
std::chrono::steady_clock::time_point lastSoundTime;
std::chrono::steady_clock::time_point lastSendTime;
public:
Shark(int x, int y, float vx, float vy, int id, int width, int height, SDL_Renderer *renderer,std::vector<Player> &players_list);
~Shark();
float getX() const { return x; };
float getY() const { return y; };
float getVx() const { return vx; };
float getVy() const { return vy; };
int getHITBOX() const { return HITBOX; };
void draw(SDL_Renderer* renderer);
void cycle();
bool isInView(Player& player);
void checkNeighborhood(Player& player, float &xpos_avg, float &ypos_avg, float &xvel_avg, float &yvel_avg, int &neighboring_player);
void updatePosition(int newX, int newY);
void checkCollision(Player& player);
};
#endif //SHARK_H

BIN
sounds/shark.wav Normal file

Binary file not shown.

BIN
video/Menu-bg.mp4 Normal file

Binary file not shown.