mirror of
https://github.com/BreizhHardware/bloubloulespoissons.git
synced 2026-01-19 00:57:26 +01:00
Compare commits
190 Commits
Procedural
...
Refactor
| Author | SHA1 | Date | |
|---|---|---|---|
| 7cf0253d30 | |||
| cfc15cdb2c | |||
|
|
c2d786c151 | ||
|
|
2ea9c91cf1 | ||
| 38dbf78a7c | |||
| 75e44df256 | |||
| 1343fe01e7 | |||
| 7d11ece61b | |||
| 5ca2cae04e | |||
| d5658422f9 | |||
|
|
23db970f42 | ||
| 23f88b2a50 | |||
|
|
e42e4061b4 | ||
|
|
439c338380 | ||
| 096d1f0aa2 | |||
|
|
ca20c3e1bd | ||
|
|
f0b0334ff8 | ||
| dec3ab3aff | |||
| 1845c2f1c9 | |||
| 44bff8bbd8 | |||
|
|
44943caaa1 | ||
| 9f0ae6ac54 | |||
| 294d7503ed | |||
| bec39bbe3d | |||
|
|
6691c70d43 | ||
|
|
f7bb656436 | ||
| 82802cd33f | |||
|
|
beeb5fd187 | ||
|
|
558e2d9b36 | ||
|
|
46ca27705e | ||
|
|
742830def8 | ||
|
|
3cc095454e | ||
|
|
d12e6fbe60 | ||
|
|
fd1e4b9ba2 | ||
|
|
3267ddb97f | ||
|
|
1ebf2b2fdf | ||
| dd2c5c00c7 | |||
|
|
4f199389f0 | ||
|
|
40b70d6ce6 | ||
|
|
b9e8b32765 | ||
|
|
037a05b106 | ||
| 23a54cc9d5 | |||
|
|
fd070bb30f | ||
|
|
d691c6af62 | ||
| 797e148f22 | |||
|
|
081272f64f | ||
|
|
03737d9c3c | ||
| cf93e05955 | |||
|
|
4fddc26d91 | ||
|
|
cea9007684 | ||
| 83c52a9a5f | |||
| 566e066bdc | |||
|
|
682963e886 | ||
| 7d1ca2196b | |||
| ad85095721 | |||
|
|
f38d39bed6 | ||
| 64a83518d0 | |||
|
|
34aa5490cb | ||
|
|
100a6b91d1 | ||
|
|
4745f6fb19 | ||
|
|
ccefcb8c87 | ||
| 17e65843b0 | |||
|
|
4d4447d250 | ||
| 479ae3c4da | |||
| bf48cdf306 | |||
| e2cc90d8a5 | |||
|
|
cbcc468fad | ||
|
|
d5520ded03 | ||
|
|
21f014a503 | ||
| 6fd472fb24 | |||
|
|
62de143515 | ||
| 14ba3cf431 | |||
| 3609bc0a4f | |||
| e15c20982e | |||
| bc6e718cfb | |||
| 93d88efbd4 | |||
|
|
b9966daac0 | ||
| 35454b2eba | |||
|
|
72fa9fede5 | ||
| f57318d739 | |||
| 98e9fedd71 | |||
|
|
02864c8e5d | ||
|
|
57750176c4 | ||
| 7d0dccf7af | |||
| 8e181b5adf | |||
| 060d6cfbc7 | |||
| cffa9855d2 | |||
| 56f4347bb4 | |||
|
|
2b414bf08a | ||
| 0908e168f4 | |||
| a1ad854c81 | |||
|
|
ae80604f29 | ||
| 098931d8b7 | |||
|
|
0871724a30 | ||
|
|
d4c8fc0504 | ||
|
|
37aa87a07f | ||
| 5fb37df1ce | |||
|
|
8b6264b7ba | ||
| 34ef1c8ace | |||
|
|
15631c95be | ||
|
|
e621bc711e | ||
| 4f65a2ab78 | |||
| d18937ddea | |||
|
|
dfecb8d663 | ||
| b4ca99c4a2 | |||
|
|
0d922391a2 | ||
| 7eaf2ac23b | |||
|
|
bb7b7a86ec | ||
| 91fb21ac79 | |||
|
|
ff23a15f08 | ||
| 5dc0d4d386 | |||
|
|
d2d5626ef0 | ||
|
|
18072b7721 | ||
| 266a087349 | |||
| b60f2e8aef | |||
|
|
ca53de3f74 | ||
|
|
57a41c8b84 | ||
|
|
513b7afb5c | ||
| ef28f48388 | |||
| 1929235cb2 | |||
|
|
9c1673bdf9 | ||
| 34251c9e3f | |||
|
|
698fc50207 | ||
|
|
3c751fb72f | ||
|
|
95ecdcc619 | ||
|
|
ea99a02ed9 | ||
| 35ef088f72 | |||
|
|
7631802cb3 | ||
|
|
c0a1b5f508 | ||
|
|
e99714f85b | ||
| fbc42ec500 | |||
| dd8c37a2c6 | |||
|
|
6b3ece56c4 | ||
|
|
b3dafa3208 | ||
|
|
8ab2a82fac | ||
|
|
200d12a67f | ||
| 4f8250d913 | |||
| f673b7f892 | |||
|
|
ceeb72d56f | ||
| bfd4f2f842 | |||
| fb9df2ae08 | |||
| aed1033f43 | |||
|
|
e11a64fc2c | ||
| 1a369af88f | |||
| db869b2cdf | |||
| 4df48ec424 | |||
| be0ae56c16 | |||
| 7c49911eb4 | |||
| 4409024e5c | |||
| a4f6db4151 | |||
|
|
08629eb290 | ||
|
|
49dd133095 | ||
| 9a2e8ba5fb | |||
|
|
df0c67f03f | ||
|
|
adc70277d5 | ||
|
|
0c4a4534d9 | ||
|
|
0aa4e62322 | ||
| eec440106a | |||
| e8c75aa187 | |||
|
|
d7c1c07da5 | ||
|
|
c8a69f5806 | ||
|
|
20e0ef08c7 | ||
| 9b166b509e | |||
| 8defdb1225 | |||
|
|
244d08dc4b | ||
| 724567537c | |||
| 48bc88059e | |||
|
|
ce32838de7 | ||
| 3828b51577 | |||
|
|
b17c8a013e | ||
|
|
e05623c330 | ||
|
|
8ea4f64a75 | ||
| 9c92b826c3 | |||
| 8d30a94fdf | |||
| bedb53f352 | |||
| 157a6895d7 | |||
|
|
7edb45fd35 | ||
|
|
1c63e16221 | ||
| 3301b0b2b4 | |||
|
|
815abc9ebf | ||
| bf0adad309 | |||
| d1029c745a | |||
| b73f71bffb | |||
| 59cdd4ea59 | |||
|
|
6f8e6255f2 | ||
|
|
5534d86889 | ||
|
|
3ce5b054b6 | ||
|
|
f4872787b0 | ||
|
|
6f7ebf2486 | ||
|
|
6d2ac388a5 |
20
.github/release-drafter.yml
vendored
Normal file
20
.github/release-drafter.yml
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
name-template: 'Release ${{ nextReleaseVersion }}'
|
||||
tag-template: 'v${{ nextReleaseVersion }}'
|
||||
categories:
|
||||
- title: '🚀 Features'
|
||||
labels:
|
||||
- 'feat'
|
||||
- title: '🐛 Bug Fixes'
|
||||
labels:
|
||||
- 'fix'
|
||||
- title: '🛠 Maintenance'
|
||||
labels:
|
||||
- 'chore'
|
||||
- title: '📚 Documentation'
|
||||
labels:
|
||||
- 'docs'
|
||||
- title: '🧪 Refactor'
|
||||
labels:
|
||||
- 'refactor'
|
||||
change-template: '- ${{ change.title }} (#${{ change.number }})'
|
||||
version-resolver: 'next'
|
||||
44
.github/workflows/build.yml
vendored
Normal file
44
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
name: Build and Test
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
|
||||
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 -DCMAKE_BUILD_TYPE=Release
|
||||
|
||||
- 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
|
||||
80
.github/workflows/release.yaml
vendored
Normal file
80
.github/workflows/release.yaml
vendored
Normal file
@@ -0,0 +1,80 @@
|
||||
name: Build and Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
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: Archive build artifacts
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: build-artifacts
|
||||
path: build/
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Download build artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
name: build-artifacts
|
||||
path: build/
|
||||
|
||||
- name: Generate release tag
|
||||
id: generate_release_tag
|
||||
uses: amitsingh-007/next-release-tag@v6.0.0
|
||||
with:
|
||||
github_token: ${{ secrets.GH_TOKEN }}
|
||||
tag_prefix: 'v'
|
||||
tag_template: 'yyyy.mm.dd.i'
|
||||
|
||||
- name: Create Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
name: Release ${{ steps.generate_release_tag.outputs.next_release_tag }}
|
||||
tag_name: ${{ steps.generate_release_tag.outputs.next_release_tag }}
|
||||
files: build/bloubloulespoissons
|
||||
generate_release_notes: false
|
||||
token: ${{ secrets.GH_TOKEN }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
|
||||
- name: Draft Release Notes
|
||||
uses: release-drafter/release-drafter@v5
|
||||
with:
|
||||
config-name: release-drafter.yml
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GH_TOKEN }}
|
||||
21
.gitignore
vendored
21
.gitignore
vendored
@@ -41,4 +41,23 @@ 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/
|
||||
cmake-build-debug-msys2
|
||||
cmake-build-debug-msys2/
|
||||
|
||||
# .vscode folder
|
||||
.vscode/
|
||||
|
||||
20
.vscode/c_cpp_properties.json
vendored
20
.vscode/c_cpp_properties.json
vendored
@@ -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
|
||||
}
|
||||
59
.vscode/settings.json
vendored
59
.vscode/settings.json
vendored
@@ -1,59 +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"
|
||||
}
|
||||
}
|
||||
48
.vscode/tasks.json
vendored
48
.vscode/tasks.json
vendored
@@ -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."
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -4,25 +4,52 @@ 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")
|
||||
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
|
||||
camera.h
|
||||
env.h
|
||||
env.cpp
|
||||
player.h
|
||||
player.cpp
|
||||
add_executable(bloubloulespoissons main.cpp
|
||||
Entities/fish.cpp
|
||||
Entities/fish.h
|
||||
Game/decors.cpp
|
||||
Game/camera.cpp
|
||||
Game/camera.h
|
||||
Entities/player.h
|
||||
Entities/player.cpp
|
||||
Utility/env.h
|
||||
Utility/env.cpp
|
||||
Game/menu.h
|
||||
Game/menu.cpp
|
||||
Network/networking.cpp
|
||||
Network/networking.h
|
||||
Network/networking_client.cpp
|
||||
Network/networking_client.h
|
||||
Entities/shark.cpp
|
||||
Entities/shark.h
|
||||
Entities/fish.h
|
||||
Utility/display.cpp
|
||||
Utility/display.h
|
||||
Utility/utility.cpp
|
||||
Utility/utility.h
|
||||
Utility/close.cpp
|
||||
Utility/close.h
|
||||
Utility/music.h
|
||||
Game/launchGameSolo.cpp
|
||||
Game/launchGameSolo.h
|
||||
Game/launchGameMulti.cpp
|
||||
Game/launchGameMulti.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")
|
||||
@@ -33,4 +60,11 @@ 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")
|
||||
target_sources(bloubloulespoissons PRIVATE resource.rc)
|
||||
endif()
|
||||
162
Entities/fish.cpp
Normal file
162
Entities/fish.cpp
Normal file
@@ -0,0 +1,162 @@
|
||||
#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
|
||||
SDL_Point points[4];
|
||||
|
||||
if (vx == 0 && vy == 0) return;
|
||||
|
||||
float angle = atan2(vy, vx);
|
||||
points[0] = {x + static_cast<int>(arrowLength * cos(angle)), y + static_cast<int>(arrowLength * sin(angle))};
|
||||
points[1] = {
|
||||
x + static_cast<int>(arrowWidth * cos(angle + M_PI / 6)),
|
||||
y + static_cast<int>(arrowWidth * sin(angle + M_PI / 6))
|
||||
};
|
||||
points[2] = {
|
||||
x + static_cast<int>(arrowWidth * cos(angle - M_PI / 6)),
|
||||
y + static_cast<int>(arrowWidth * sin(angle - M_PI / 6))
|
||||
};
|
||||
points[3] = points[0];
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); // Vert
|
||||
SDL_RenderDrawLines(renderer, points, 4);
|
||||
}
|
||||
|
||||
void Fish::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, 255, 0, 0, 255); // Red
|
||||
SDL_RenderFillRect(renderer, &rect);
|
||||
}
|
||||
//drawArrow(renderer, x + width / 2, y + height / 2, vx, vy);
|
||||
}
|
||||
|
||||
bool Fish::isInView(Fish &other) {
|
||||
return (other.getX() >= x - VISUAL_RANGE && other.getX() <= x + VISUAL_RANGE &&
|
||||
other.getY() >= y - VISUAL_RANGE && other.getY() <= y + VISUAL_RANGE);
|
||||
}
|
||||
|
||||
bool Fish::isClose(Fish &other) {
|
||||
return (other.getX() >= x - PROTECTED_RANGE && other.getX() <= x + PROTECTED_RANGE &&
|
||||
other.getY() >= y - PROTECTED_RANGE && other.getY() <= y + PROTECTED_RANGE);
|
||||
}
|
||||
|
||||
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 (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) {
|
||||
xpos_avg /= neighboring_boids;
|
||||
ypos_avg /= neighboring_boids;
|
||||
xvel_avg /= neighboring_boids;
|
||||
yvel_avg /= neighboring_boids;
|
||||
vx += (xpos_avg - x) * CENTERING_FACTOR + (xvel_avg - vx) * MATCHING_FACTOR;
|
||||
vy += (ypos_avg - y) * CENTERING_FACTOR + (yvel_avg - vy) * MATCHING_FACTOR;
|
||||
}
|
||||
vx += close_dx * AVOIDANCE_FORCE;
|
||||
vy += close_dy * AVOIDANCE_FORCE;
|
||||
|
||||
if (y <= 0) {
|
||||
vy += TURN_FACTOR;
|
||||
}
|
||||
if (y >= (ENV_WIDTH - MARGIN_HEIGHT)) {
|
||||
vy -= TURN_FACTOR;
|
||||
}
|
||||
if (x <= 0) {
|
||||
vx += TURN_FACTOR;
|
||||
}
|
||||
if (x >= (ENV_WIDTH - MARGIN_WIDTH)) {
|
||||
vx -= TURN_FACTOR;
|
||||
}
|
||||
|
||||
if (biasdir == 1) {
|
||||
vx = (1 - BIASVALUE) * vx + (BIASVALUE * 1);
|
||||
} else if (biasdir == 0) {
|
||||
vx = (1 - BIASVALUE) * vx + (BIASVALUE * -1);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
@@ -6,8 +6,8 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "camera.h"
|
||||
#include "env.h"
|
||||
#include "../Game/camera.h"
|
||||
#include "../Utility/env.h"
|
||||
|
||||
class Fish {
|
||||
private:
|
||||
@@ -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,12 +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);
|
||||
|
||||
static bool SortByX(const Fish &a, const Fish &b) {
|
||||
return a.getX() < b.getX();
|
||||
}
|
||||
|
||||
static void insertionSort(std::vector<Fish>& school) ;
|
||||
|
||||
// Copy constructor
|
||||
Fish(const Fish& other);
|
||||
|
||||
// Copy assignment operator
|
||||
Fish& operator=(const Fish& other);
|
||||
};
|
||||
|
||||
#endif //FISH_H
|
||||
251
Entities/player.cpp
Normal file
251
Entities/player.cpp
Normal file
@@ -0,0 +1,251 @@
|
||||
#include "player.h"
|
||||
|
||||
void Player::updatePlayerPos(int x, int y) {
|
||||
this->x = x;
|
||||
this->y = y;
|
||||
this->playerPosForRender.x = x;
|
||||
this->playerPosForRender.y = y;
|
||||
};
|
||||
|
||||
void Player::updatePlayerSpeed(int playerSpeed) {
|
||||
this->playerSpeed = playerSpeed;
|
||||
};
|
||||
|
||||
std::tuple<int, int> Player::getPlayerPos() const {
|
||||
return std::make_tuple(this->x, this->y);
|
||||
};
|
||||
|
||||
int Player::getPlayerSpeed() {
|
||||
return playerSpeed;
|
||||
};
|
||||
|
||||
|
||||
void Player::draw(SDL_Renderer* renderer) {
|
||||
switch (this->ticks) {
|
||||
case 0:
|
||||
this->currentSprite = PLAYER_SPRITE_1;
|
||||
break;
|
||||
case 5:
|
||||
this->currentSprite = PLAYER_SPRITE_2;
|
||||
break;
|
||||
case 8:
|
||||
this->currentSprite = PLAYER_SPRITE_3;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (this->ticks >= 8) {
|
||||
this->ticks = 0;
|
||||
} else {
|
||||
this->ticks++;
|
||||
}
|
||||
|
||||
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) {
|
||||
const Uint8* keystate = SDL_GetKeyboardState(NULL);
|
||||
Camera& camera = Camera::getInstance();
|
||||
|
||||
int tempX = this->x;
|
||||
int tempY = this->y;
|
||||
int speed = this->playerSpeed;
|
||||
bool isSprinting = false;
|
||||
if (keystate[SDL_SCANCODE_LSHIFT]) {
|
||||
speed = this->playerSpeed * 2;
|
||||
isSprinting = true;
|
||||
}
|
||||
|
||||
bool moved = false;
|
||||
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();
|
||||
}
|
||||
} 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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
this->updatePlayerPos(tempX, tempY);
|
||||
}
|
||||
}
|
||||
if (moved) {
|
||||
lastMoveTime = SDL_GetTicks();
|
||||
if (!isSprinting) {
|
||||
this->energy -= 0.1f;
|
||||
} else {
|
||||
this->energy -= 0.2f;
|
||||
}
|
||||
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 >= 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;
|
||||
}
|
||||
}
|
||||
|
||||
void Player::drawEnergyBar(SDL_Renderer* renderer) {
|
||||
SDL_Rect energyBarBackground = {10, 10, 200, 20};
|
||||
SDL_Rect energyBarForeground = {10, 10, static_cast<int>(2 * this->energy), 20};
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
|
||||
SDL_RenderFillRect(renderer, &energyBarBackground);
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255);
|
||||
SDL_RenderFillRect(renderer, &energyBarForeground);
|
||||
}
|
||||
|
||||
int Player::getPlayerId() const {
|
||||
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;
|
||||
}
|
||||
@@ -5,6 +5,15 @@
|
||||
#include <SDL2/SDL_image.h>
|
||||
#include <iostream>
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
#include <syncstream>
|
||||
#include <tuple>
|
||||
#include "../Network/networking_client.h"
|
||||
#include "../Game/camera.h"
|
||||
#include "fish.h"
|
||||
#include <syncstream>
|
||||
#include <tuple>
|
||||
#include "../Network/networking_client.h"
|
||||
|
||||
|
||||
enum playerData {
|
||||
@@ -25,6 +34,8 @@ 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;
|
||||
SDL_Rect playerPosForRender = {0, 0, PLAYER_SIZE_X, PLAYER_SIZE_Y};
|
||||
@@ -33,11 +44,17 @@ class Player {
|
||||
{326, 73, 112, 117},
|
||||
{528, 73, 112, 117}
|
||||
};
|
||||
|
||||
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) {
|
||||
@@ -50,10 +67,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() const;
|
||||
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
|
||||
143
Entities/shark.cpp
Normal file
143
Entities/shark.cpp
Normal file
@@ -0,0 +1,143 @@
|
||||
//
|
||||
// Created by cfouche on 09/12/24.
|
||||
//
|
||||
|
||||
#define sharkIMG "../img/shark.png"
|
||||
#include "shark.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;
|
||||
// }
|
||||
|
||||
// approachingSound = Mix_LoadWAV("../sounds/Shark-approching.wav");
|
||||
// if (approachingSound == nullptr) {
|
||||
// std::cerr << "Erreur de chargement du son d'approche 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);
|
||||
//Mix_PlayChannel(SOUND_CHANNEL, approachingSound, 0);
|
||||
musicManager.playMusic("Shark-approaching");
|
||||
musicManager.pauseMusic("Playing");
|
||||
}
|
||||
if (!isInView(player)) {
|
||||
// Cut the approach sound
|
||||
musicManager.stopMusic("Shark-approaching");
|
||||
musicManager.resumeMusic("Playing");
|
||||
// Mix_HaltChannel(SOUND_CHANNEL);
|
||||
}
|
||||
}
|
||||
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(SOUND_CHANNEL, sharkSound, 0);
|
||||
// }
|
||||
musicManager.playMusic("Shark");
|
||||
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;
|
||||
// }
|
||||
|
||||
// if (approachingSound) {
|
||||
// Mix_FreeChunk(approachingSound);
|
||||
// approachingSound = nullptr;
|
||||
// }
|
||||
}
|
||||
|
||||
void Shark::updatePosition(int newX, int newY) {
|
||||
x = newX;
|
||||
y = newY;
|
||||
}
|
||||
63
Entities/shark.h
Normal file
63
Entities/shark.h
Normal file
@@ -0,0 +1,63 @@
|
||||
//
|
||||
// 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>
|
||||
#include "../Network/networking.h"
|
||||
|
||||
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;
|
||||
// Mix_Chunk* approachingSound;
|
||||
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
|
||||
@@ -3,9 +3,6 @@
|
||||
//
|
||||
|
||||
#include "decors.h"
|
||||
#include <iostream>
|
||||
|
||||
#include "env.h"
|
||||
|
||||
void Rock::draw(SDL_Renderer* renderer) const{
|
||||
Camera& camera = Camera::getInstance();
|
||||
@@ -35,7 +32,20 @@ void Kelp::draw(SDL_Renderer* renderer) const {
|
||||
}
|
||||
}
|
||||
|
||||
void generateProceduralDecorations(std::vector<Kelp>&kelps, std::vector<Rock>&rocks, int envHeight, int envWidth , SDL_Renderer* renderer) {
|
||||
void Coral::draw(SDL_Renderer* renderer) const {
|
||||
Camera& camera = Camera::getInstance();
|
||||
int cameraX = camera.getX();
|
||||
int cameraY = camera.getY();
|
||||
SDL_Rect coralRect = { x - cameraX, y - cameraY, size, size };
|
||||
if (texturesVector[2] != nullptr) {
|
||||
SDL_RenderCopy(renderer, texturesVector[2], nullptr, &coralRect);
|
||||
} else {
|
||||
SDL_SetRenderDrawColor(renderer, r, g, b, 255);
|
||||
SDL_RenderFillRect(renderer, &coralRect);
|
||||
}
|
||||
}
|
||||
|
||||
void generateProceduralDecorations(std::vector<Kelp>& kelps, std::vector<Rock>& rocks, std::vector<Coral>& corals,int envHeight, int envWidth, SDL_Renderer* renderer) {
|
||||
std::srand(std::time(0));
|
||||
|
||||
//Generate Kelp
|
||||
@@ -61,4 +71,15 @@ void generateProceduralDecorations(std::vector<Kelp>&kelps, std::vector<Rock>&ro
|
||||
int b = 100 + std::rand() % 156;
|
||||
rocks.emplace_back(Rock(x, y, size, r, g, b, renderer));
|
||||
}
|
||||
|
||||
int numCoral = 10 + std::rand() % 10;
|
||||
for (int i = 0; i < numCoral; i++) {
|
||||
int x = std::rand() % envWidth;
|
||||
int y = envHeight - (std::rand() % static_cast<int>(envHeight * 0.2));
|
||||
int size = 250 + std::rand() % 20;
|
||||
int r = 100 + std::rand() % 156;
|
||||
int g = 100 + std::rand() % 156;
|
||||
int b = 100 + std::rand() % 156;
|
||||
corals.emplace_back(Coral(x, y, size, r, g, b, renderer));
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,9 @@
|
||||
#include <ctime>
|
||||
#include <cstdlib>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include "camera.h"
|
||||
#include "../Utility/env.h"
|
||||
|
||||
class Rock {
|
||||
public:
|
||||
@@ -38,7 +40,18 @@ private:
|
||||
Uint8 b;
|
||||
};
|
||||
|
||||
void generateProceduralDecorations(std::vector<Kelp>& kelps, std::vector<Rock>& rocks, int envHeight, int envWidth, SDL_Renderer* renderer);
|
||||
class Coral {
|
||||
public:
|
||||
Coral(int x, int y, int size, Uint8 r, Uint8 g, Uint8 b, SDL_Renderer* renderer) : x(x), y(y), size(size), r(r), g(g), b(b) {};
|
||||
void draw(SDL_Renderer* renderer) const;
|
||||
int x;
|
||||
int y;
|
||||
private:
|
||||
int size;
|
||||
Uint8 r, g, b;
|
||||
};
|
||||
|
||||
void generateProceduralDecorations(std::vector<Kelp>& kelps, std::vector<Rock>& rocks, std::vector<Coral>& corals,int envHeight, int envWidth, SDL_Renderer* renderer);
|
||||
|
||||
|
||||
#endif //DECORS_H
|
||||
195
Game/launchGameMulti.cpp
Normal file
195
Game/launchGameMulti.cpp
Normal file
@@ -0,0 +1,195 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#include "launchGameMulti.h"
|
||||
|
||||
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;
|
||||
|
||||
musicManager.playMusic("Playing");
|
||||
|
||||
// Mix_HaltMusic();
|
||||
|
||||
// backgroundMusic = Mix_LoadMUS("../sounds/Playing.wav");
|
||||
// if (backgroundMusic == nullptr) {
|
||||
// std::cerr << "Erreur de chargement de la musique: " << Mix_GetError() << std::endl;
|
||||
// return false;
|
||||
// }
|
||||
// Mix_VolumeMusic(MIX_MAX_VOLUME / 4);
|
||||
// if (Mix_PlayMusic(backgroundMusic, -1) == -1) {
|
||||
// std::cerr << "Erreur de lecture de la musique: " << Mix_GetError() << std::endl;
|
||||
// return false;
|
||||
// }
|
||||
// Mix_PlayMusic(backgroundMusic, -1);
|
||||
|
||||
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;
|
||||
std::vector<std::thread> threads;
|
||||
int fishPerThread = school.size() / std::thread::hardware_concurrency();
|
||||
int thread_id = 0;
|
||||
for (int i = 0; i < school.size(); i += fishPerThread) {
|
||||
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);
|
||||
|
||||
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]));
|
||||
|
||||
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;
|
||||
|
||||
}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;
|
||||
}
|
||||
school.clear();
|
||||
players.clear();
|
||||
eventHandler.triggerEvent("playerLost");
|
||||
}
|
||||
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;
|
||||
}
|
||||
school.clear();
|
||||
players.clear();
|
||||
eventHandler.triggerEvent("playerLost");
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
20
Game/launchGameMulti.h
Normal file
20
Game/launchGameMulti.h
Normal file
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#ifndef LAUNCHGAMEMULTI_H
|
||||
#define LAUNCHGAMEMULTI_H
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <algorithm>
|
||||
|
||||
#include "../Utility/env.h"
|
||||
#include "decors.h"
|
||||
#include "../Entities/fish.h"
|
||||
#include "../Utility/utility.h"
|
||||
|
||||
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);
|
||||
|
||||
#endif //LAUNCHGAMEMULTI_H
|
||||
103
Game/launchGameSolo.cpp
Normal file
103
Game/launchGameSolo.cpp
Normal file
@@ -0,0 +1,103 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#include "launchGameSolo.h"
|
||||
|
||||
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[]) {
|
||||
// if (!initSDL()) {
|
||||
// std::cerr << "Failed to initialize!" << std::endl;
|
||||
// return -1;
|
||||
// }
|
||||
|
||||
game_running = true;
|
||||
|
||||
|
||||
musicManager.playMusic("Playing");
|
||||
|
||||
// Mix_HaltMusic();
|
||||
|
||||
// backgroundMusic = Mix_LoadMUS("../sounds/Playing.wav");
|
||||
// if (backgroundMusic == nullptr) {
|
||||
// std::cerr << "Erreur de chargement de la musique: " << Mix_GetError() << std::endl;
|
||||
// return false;
|
||||
// }
|
||||
// Mix_VolumeMusic(MIX_MAX_VOLUME / 4);
|
||||
// if (Mix_PlayMusic(backgroundMusic, -1) == -1) {
|
||||
// std::cerr << "Erreur de lecture de la musique: " << Mix_GetError() << std::endl;
|
||||
// return false;
|
||||
// }
|
||||
// Mix_PlayMusic(backgroundMusic, -1);
|
||||
|
||||
std::vector<Kelp> kelps;
|
||||
std::vector<Rock> rocks;
|
||||
std::vector<Coral> corals;
|
||||
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) {
|
||||
int x = rand() % ENV_WIDTH;
|
||||
int y = rand() % ENV_HEIGHT;
|
||||
double speedX = 0.1;
|
||||
double speedY = 0.1;
|
||||
int textureIndex = rand() % fishCount;
|
||||
int gender = rand() % 2 == 0 ? 1 : 0;
|
||||
|
||||
school.emplace_back(x, y, speedX, speedY, school, i, 75, 75, renderer, gender, fishTextures[textureIndex]);
|
||||
}
|
||||
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;
|
||||
school.clear();
|
||||
players.clear();
|
||||
eventHandler.triggerEvent("playerLost");
|
||||
return 0;
|
||||
}
|
||||
20
Game/launchGameSolo.h
Normal file
20
Game/launchGameSolo.h
Normal file
@@ -0,0 +1,20 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#ifndef LAUNCGAMESOLO_H
|
||||
#define LAUNCGAMESOLO_H
|
||||
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <thread>
|
||||
#include "../Utility/env.h"
|
||||
#include "../Utility/utility.h"
|
||||
#include "../Entities/fish.h"
|
||||
#include "../Entities/shark.h"
|
||||
#include "decors.h"
|
||||
|
||||
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[]);
|
||||
|
||||
#endif //LAUNCGAMESOLO_H
|
||||
328
Game/menu.cpp
Normal file
328
Game/menu.cpp
Normal file
@@ -0,0 +1,328 @@
|
||||
#include "menu.h"
|
||||
|
||||
|
||||
void drawRoundedRectWithGradient(SDL_Renderer* renderer, SDL_Rect rect, int radius, SDL_Color startColor, SDL_Color endColor, int gradientWidth) {
|
||||
for (int i = 0; i < gradientWidth; i++) {
|
||||
Uint8 r = startColor.r + i * (endColor.r - startColor.r) / gradientWidth;
|
||||
Uint8 g = startColor.g + i * (endColor.g - startColor.g) / gradientWidth;
|
||||
Uint8 b = startColor.b + i * (endColor.b - startColor.b) / gradientWidth;
|
||||
Uint8 a = startColor.a + i * (endColor.a - startColor.a) / gradientWidth;
|
||||
|
||||
SDL_Color gradientColor = {r, g, b, a};
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, gradientColor.r, gradientColor.g, gradientColor.b, gradientColor.a);
|
||||
SDL_Rect gradientRect = {
|
||||
rect.x - i,
|
||||
rect.y - i,
|
||||
rect.w + 2 * i,
|
||||
rect.h + 2 * i
|
||||
};
|
||||
|
||||
auto drawRoundedCorners = [&](int x, int y, int r) {
|
||||
for (int dy = -r; dy <= r; dy++) {
|
||||
for (int dx = -r; dx <= r; dx++) {
|
||||
if (dx * dx + dy * dy <= r * r) {
|
||||
SDL_RenderDrawPoint(renderer, x + dx, y + dy);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
drawRoundedCorners(gradientRect.x + radius, gradientRect.y + radius, radius);
|
||||
drawRoundedCorners(gradientRect.x + gradientRect.w - radius, gradientRect.y + radius, radius);
|
||||
drawRoundedCorners(gradientRect.x + radius, gradientRect.y + gradientRect.h - radius, radius);
|
||||
drawRoundedCorners(gradientRect.x + gradientRect.w - radius, gradientRect.y + gradientRect.h - radius, radius);
|
||||
|
||||
SDL_Rect top = {gradientRect.x + radius, gradientRect.y, gradientRect.w - 2 * radius, radius};
|
||||
SDL_Rect bottom = {gradientRect.x + radius, gradientRect.y + gradientRect.h - radius, gradientRect.w - 2 * radius, radius};
|
||||
SDL_Rect left = {gradientRect.x, gradientRect.y + radius, radius, gradientRect.h - 2 * radius};
|
||||
SDL_Rect right = {gradientRect.x + gradientRect.w - radius, gradientRect.y + radius, radius, gradientRect.h - 2 * radius};
|
||||
SDL_Rect center = {gradientRect.x + radius, gradientRect.y + radius, gradientRect.w - 2 * radius, gradientRect.h - 2 * radius};
|
||||
|
||||
SDL_RenderDrawRect(renderer, &top);
|
||||
SDL_RenderDrawRect(renderer, &bottom);
|
||||
SDL_RenderDrawRect(renderer, &left);
|
||||
SDL_RenderDrawRect(renderer, &right);
|
||||
}
|
||||
}
|
||||
|
||||
void drawRoundedRect(SDL_Renderer* renderer, SDL_Rect rect, int radius, SDL_Color color) {
|
||||
SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);
|
||||
|
||||
auto drawRoundedCorners = [&](int x, int y, int r) {
|
||||
for (int dy = -r; dy <= r; dy++) {
|
||||
for (int dx = -r; dx <= r; dx++) {
|
||||
if (dx * dx + dy * dy <= r * r) {
|
||||
SDL_RenderDrawPoint(renderer, x + dx, y + dy);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
drawRoundedCorners(rect.x + radius, rect.y + radius, radius);
|
||||
drawRoundedCorners(rect.x + rect.w - radius, rect.y + radius, radius);
|
||||
drawRoundedCorners(rect.x + radius, rect.y + rect.h - radius, radius);
|
||||
drawRoundedCorners(rect.x + rect.w - radius, rect.y + rect.h - radius, radius);
|
||||
|
||||
SDL_Rect top = {rect.x + radius, rect.y, rect.w - 2 * radius, radius};
|
||||
SDL_Rect bottom = {rect.x + radius, rect.y + rect.h - radius, rect.w - 2 * radius, radius};
|
||||
SDL_Rect left = {rect.x, rect.y + radius, radius, rect.h - 2 * radius};
|
||||
SDL_Rect right = {rect.x + rect.w - radius, rect.y + radius, radius, rect.h - 2 * radius};
|
||||
SDL_Rect center = {rect.x + radius, rect.y + radius, rect.w - 2 * radius, rect.h - 2 * radius};
|
||||
|
||||
SDL_RenderFillRect(renderer, &top);
|
||||
SDL_RenderFillRect(renderer, &bottom);
|
||||
SDL_RenderFillRect(renderer, &left);
|
||||
SDL_RenderFillRect(renderer, &right);
|
||||
SDL_RenderFillRect(renderer, ¢er);
|
||||
}
|
||||
|
||||
|
||||
std::string Menu::getCurrentPageName() {
|
||||
if (currentPage == -1) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return pages[currentPage].title;
|
||||
}
|
||||
|
||||
void Menu::draw(SDL_Renderer* renderer) {
|
||||
SDL_RenderClear(renderer);
|
||||
SDL_RenderCopy(renderer, backgroundTxt, nullptr, &backgroundRect);
|
||||
|
||||
if (pages.size() > 0) {
|
||||
if (currentPage == -1 && pages.size() > 0) {
|
||||
currentPage = 0;
|
||||
}
|
||||
|
||||
for (ImagePage image : pages[currentPage].images) {
|
||||
SDL_RenderCopy(renderer, image.image, nullptr, &image.rect);
|
||||
}
|
||||
|
||||
for (Text& text : pages[currentPage].texts) {
|
||||
SDL_RenderCopy(renderer, text.txt, nullptr, &text.rect);
|
||||
}
|
||||
|
||||
int mouseX, mouseY;
|
||||
SDL_GetMouseState(&mouseX, &mouseY);
|
||||
|
||||
bool hover = false;
|
||||
for (Button& button : pages[currentPage].buttons) {
|
||||
// Activer le blending pour l'arrière-plan du bouton
|
||||
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
|
||||
SDL_SetRenderDrawColor(renderer, button.bgColor.r, button.bgColor.g, button.bgColor.b, button.bgColor.a);
|
||||
SDL_RenderFillRect(renderer, &button.rect);
|
||||
|
||||
// Dessiner la bordure du bouton
|
||||
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_NONE);
|
||||
SDL_SetRenderDrawColor(renderer, button.borderColor.r, button.borderColor.g, button.borderColor.b, button.borderColor.a);
|
||||
SDL_Rect borderRect = {button.rect.x - button.borderWidth, button.rect.y - button.borderWidth, button.rect.w + 2 * button.borderWidth, button.rect.h + 2 * button.borderWidth};
|
||||
SDL_RenderDrawRect(renderer, &borderRect);
|
||||
|
||||
SDL_RenderCopy(renderer, button.txt, nullptr, &button.txtRect);
|
||||
|
||||
if (button.isTextInput) {
|
||||
TTF_Font* font_txt = TTF_OpenFont("../fonts/arial.ttf", 24);
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font_txt, button.inputText.c_str(), button.fontColor);
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_Rect inputRect = {button.rect.x + 5, button.rect.y + 5, button.rect.w - 10, button.rect.h - 10};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &inputRect);
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
TTF_CloseFont(font_txt);
|
||||
}
|
||||
|
||||
if (mouseX >= button.rect.x && mouseX <= button.rect.x + button.rect.w &&
|
||||
mouseY >= button.rect.y && mouseY <= button.rect.y + button.rect.h) {
|
||||
hover = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (hover) {
|
||||
SDL_Cursor* cursor = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
|
||||
SDL_SetCursor(cursor);
|
||||
} else {
|
||||
SDL_Cursor* cursor = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
|
||||
SDL_SetCursor(cursor);
|
||||
}
|
||||
}
|
||||
|
||||
SDL_RenderPresent(renderer);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Menu::handleClickedButton() {
|
||||
SDL_Event event;
|
||||
while (SDL_PollEvent(&event)) {
|
||||
if (event.type == SDL_QUIT) {
|
||||
running = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type == SDL_MOUSEBUTTONDOWN) {
|
||||
int mouseX, mouseY;
|
||||
SDL_GetMouseState(&mouseX, &mouseY);
|
||||
activeTextInputIndex = -1;
|
||||
for (int i = 0; i < pages[currentPage].buttons.size(); ++i) {
|
||||
Button& button = pages[currentPage].buttons[i];
|
||||
if (mouseX >= button.rect.x && mouseX <= button.rect.x + button.rect.w &&
|
||||
mouseY >= button.rect.y && mouseY <= button.rect.y + button.rect.h) {
|
||||
if (button.isTextInput) {
|
||||
// Activer le champ de texte
|
||||
SDL_StartTextInput();
|
||||
activeTextInputIndex = i; // Mettre à jour l'élément de texte actif
|
||||
} else {
|
||||
button.callback();
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (event.type == SDL_TEXTINPUT) {
|
||||
if (activeTextInputIndex != -1) {
|
||||
Button& button = pages[currentPage].buttons[activeTextInputIndex];
|
||||
if (button.isTextInput) {
|
||||
button.inputText += event.text.text;
|
||||
}
|
||||
}
|
||||
} else if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_BACKSPACE) {
|
||||
if (activeTextInputIndex != -1) {
|
||||
Button& button = pages[currentPage].buttons[activeTextInputIndex];
|
||||
if (button.isTextInput && !button.inputText.empty()) {
|
||||
button.inputText.pop_back();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Menu::hide(){
|
||||
shown = false;
|
||||
}
|
||||
|
||||
void Menu::show(){
|
||||
shown = true;
|
||||
}
|
||||
|
||||
bool Menu::isShown(){
|
||||
return shown;
|
||||
}
|
||||
|
||||
void Menu::changePage(std::string title){
|
||||
for(int i = 0; i < pages.size(); i++){
|
||||
if(pages[i].title == title){
|
||||
currentPage = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Menu::addButton(std::string page, int x, int y, int w, int h, std::string text, int size, std::function<void()> callback, bool isTextInput) {
|
||||
for (Page& p : pages) {
|
||||
if (p.title == page) {
|
||||
TTF_Font* font_txt = TTF_OpenFont("../fonts/arial.ttf", size);
|
||||
if (font_txt == nullptr) {
|
||||
std::cerr << "Erreur de chargement de la police: " << TTF_GetError() << std::endl;
|
||||
}
|
||||
Button button;
|
||||
button.rect = {x, y, w, h};
|
||||
int textWidth = w / 2;
|
||||
int textHeight = h / 1.5;
|
||||
button.txtRect = {x + (w / 2) - (textWidth / 2), y + (h / 2) - (textHeight / 2), textWidth, textHeight};
|
||||
button.fontColor = {255, 255, 255};
|
||||
button.bgColor = {0, 0, 0, 75}; // Fond noir avec opacité de 13%
|
||||
button.borderColor = {40, 120, 122, 255}; // Couleur de la bordure
|
||||
button.borderWidth = 5; // Largeur de la bordure
|
||||
button.borderRadius = 17; // Rayon de la bordure
|
||||
button.isTextInput = isTextInput;
|
||||
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font_txt, text.c_str(), button.fontColor);
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_FreeSurface(textSurface);
|
||||
button.txt = textTexture;
|
||||
button.callback = callback;
|
||||
button.startGradientColor = {40, 120, 122, 255};
|
||||
button.endGradientColor = {55, 171, 189, 255};
|
||||
button.gradientWidth = 10;
|
||||
|
||||
p.buttons.push_back(button);
|
||||
TTF_CloseFont(font_txt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Menu::addText(std::string page, int x, int y, int w, int h, std::string text, int size){
|
||||
for(Page& p : pages){
|
||||
if(p.title == page){
|
||||
TTF_Font* font_txt = TTF_OpenFont("../fonts/arial.ttf", size);
|
||||
if (font_txt == nullptr) {
|
||||
std::cerr << "Erreur de chargement de la police: " << TTF_GetError() << std::endl;
|
||||
}
|
||||
Text txt;
|
||||
txt.rect = {x, y, w, h};
|
||||
txt.fontColor = {255, 255, 255};
|
||||
txt.txtRect = {x, y, w, h};
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font_txt, text.c_str(), txt.fontColor);
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_FreeSurface(textSurface);
|
||||
txt.txt = textTexture;
|
||||
p.texts.push_back(txt);
|
||||
TTF_CloseFont(font_txt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Menu::addPage(std::string title){
|
||||
Page page;
|
||||
page.title = title;
|
||||
pages.push_back(page);
|
||||
}
|
||||
|
||||
|
||||
std::vector<Button> Menu::getButtons(){
|
||||
return pages[currentPage].buttons;
|
||||
}
|
||||
|
||||
void Menu::addImage(std::string page, int x, int y, int w, int h, std::string path) {
|
||||
for (Page& p : pages) {
|
||||
if (p.title == page) {
|
||||
SDL_Surface* imageSurface = IMG_Load(path.c_str());
|
||||
if (imageSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'image: " << IMG_GetError() << std::endl;
|
||||
return;
|
||||
}
|
||||
SDL_Texture* imageTexture = SDL_CreateTextureFromSurface(renderer, imageSurface);
|
||||
SDL_FreeSurface(imageSurface);
|
||||
SDL_Rect imageRect = {x, y, w, h};
|
||||
|
||||
p.images.push_back(ImagePage(imageTexture, imageRect));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Menu::drawLost(SDL_Renderer* renderer) {
|
||||
// Charger l'image perdu.png
|
||||
SDL_Surface* lostSurface = IMG_Load("../img/perdu.png");
|
||||
if (lostSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'image perdu.png: " << IMG_GetError() << std::endl;
|
||||
return;
|
||||
}
|
||||
SDL_Texture* lostTexture = SDL_CreateTextureFromSurface(renderer, lostSurface);
|
||||
SDL_FreeSurface(lostSurface);
|
||||
|
||||
// Définir la transparence (alpha) de l'image
|
||||
SDL_SetTextureBlendMode(lostTexture, SDL_BLENDMODE_BLEND);
|
||||
SDL_SetTextureAlphaMod(lostTexture, 128); // 128 pour 50% de transparence
|
||||
|
||||
// Obtenir les dimensions de la fenêtre
|
||||
int windowWidth, windowHeight;
|
||||
SDL_GetRendererOutputSize(renderer, &windowWidth, &windowHeight);
|
||||
|
||||
// Définir le rectangle de destination pour l'image
|
||||
SDL_Rect destRect = {0, 0, windowWidth, windowHeight};
|
||||
|
||||
// Dessiner l'image
|
||||
SDL_RenderCopy(renderer, lostTexture, nullptr, &destRect);
|
||||
|
||||
// Détruire la texture après utilisation
|
||||
SDL_DestroyTexture(lostTexture);
|
||||
}
|
||||
103
Game/menu.h
Normal file
103
Game/menu.h
Normal file
@@ -0,0 +1,103 @@
|
||||
#include <iostream>
|
||||
#include "../Utility/env.h"
|
||||
#include <SDL2/SDL.h>
|
||||
#include <SDL2/SDL_image.h>
|
||||
#include <SDL2/SDL_ttf.h>
|
||||
#include <vector>
|
||||
#include <functional>
|
||||
|
||||
#ifndef MENU_H
|
||||
#define MENU_H
|
||||
|
||||
struct Button {
|
||||
SDL_Rect rect;
|
||||
SDL_Texture* txt;
|
||||
SDL_Color fontColor;
|
||||
SDL_Color bgColor;
|
||||
SDL_Rect txtRect;
|
||||
std::function<void()> callback;
|
||||
bool isTextInput = false;
|
||||
std::string inputText;
|
||||
SDL_Color borderColor;
|
||||
int borderWidth;
|
||||
int borderRadius;
|
||||
SDL_Color startGradientColor;
|
||||
SDL_Color endGradientColor;
|
||||
int gradientWidth;
|
||||
};
|
||||
|
||||
struct Text {
|
||||
SDL_Rect rect;
|
||||
SDL_Texture* txt;
|
||||
SDL_Color fontColor;
|
||||
SDL_Rect txtRect;
|
||||
};
|
||||
|
||||
struct ImagePage {
|
||||
SDL_Texture* image;
|
||||
SDL_Rect rect;
|
||||
};
|
||||
|
||||
struct Page {
|
||||
std::string title;
|
||||
std::vector<Button> buttons;
|
||||
std::vector<Text> texts;
|
||||
std::vector<ImagePage> images;
|
||||
};
|
||||
|
||||
|
||||
void drawRoundedRectWithGradient(SDL_Renderer* renderer, SDL_Rect rect, int radius, SDL_Color startColor, SDL_Color endColor, int gradientWidth);
|
||||
void drawRoundedRect(SDL_Renderer* renderer, SDL_Rect rect, int radius, SDL_Color color);
|
||||
|
||||
class Menu {
|
||||
private:
|
||||
SDL_Texture* backgroundTxt = nullptr;
|
||||
SDL_Rect backgroundRect = {0, 0, windowWidth, windowHeight};
|
||||
std::string menuTitle = "BloubBloub les poissons";
|
||||
SDL_Renderer* renderer;
|
||||
bool shown = true;
|
||||
std::vector<Page> pages;
|
||||
int currentPage = -1;
|
||||
int activeTextInputIndex = -1;
|
||||
|
||||
|
||||
public:
|
||||
Menu(SDL_Renderer* renderer){
|
||||
this->renderer = renderer;
|
||||
SDL_Surface* backgroundSurface = IMG_Load("../img/menu/background.png");
|
||||
if (backgroundSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'image du menu: " << IMG_GetError() << std::endl;
|
||||
} else {
|
||||
backgroundTxt = SDL_CreateTextureFromSurface(renderer, backgroundSurface);
|
||||
SDL_FreeSurface(backgroundSurface);
|
||||
}
|
||||
};
|
||||
|
||||
void handleClickedButton();
|
||||
|
||||
void hide();
|
||||
|
||||
void show();
|
||||
|
||||
bool isShown();
|
||||
|
||||
void draw(SDL_Renderer* renderer);
|
||||
|
||||
void changePage(std::string title);
|
||||
|
||||
std::string getCurrentPageName();
|
||||
|
||||
void addButton(std::string page, int x, int y, int w, int h, std::string text, int size, std::function<void()> callback, bool isTextInput = false);
|
||||
|
||||
void addText(std::string page, int x, int y, int w, int h, std::string text, int size);
|
||||
|
||||
void addPage(std::string title);
|
||||
|
||||
void addImage(std::string page, int x, int y, int w, int h, std::string path);
|
||||
|
||||
std::vector<Button> getButtons();
|
||||
|
||||
void drawLost(SDL_Renderer* renderer);
|
||||
};
|
||||
|
||||
#endif
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal 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>.
|
||||
257
Network/networking.cpp
Normal file
257
Network/networking.cpp
Normal file
@@ -0,0 +1,257 @@
|
||||
//
|
||||
// Created by BreizhHardware on 04/12/2024.
|
||||
//
|
||||
|
||||
#include "networking.h"
|
||||
#include "../Entities/player.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;
|
||||
}
|
||||
|
||||
std::vector<PlayerInfo> getAllPlayers() {
|
||||
std::vector<PlayerInfo> playersInfo;
|
||||
for (const auto& player : players_server) {
|
||||
auto [x, y] = player.getPlayerPos();
|
||||
playersInfo.push_back({player.getPlayerId(), x, y});
|
||||
}
|
||||
return playersInfo;
|
||||
}
|
||||
|
||||
void sendPlayerListToNewClient(int clientSocket) {
|
||||
std::vector<PlayerInfo> players = getAllPlayers();
|
||||
|
||||
int playerCount = players.size();
|
||||
std::string message = "playerList;" + std::to_string(playerCount) + ";";
|
||||
sendMessage(server, message);
|
||||
|
||||
for (const auto& player : players) {
|
||||
std::string playerInfo = std::to_string(player.id) + "," + std::to_string(player.x) + "," + std::to_string(player.y) + ";";
|
||||
sendMessage(server, playerInfo);
|
||||
}
|
||||
}
|
||||
37
Network/networking.h
Normal file
37
Network/networking.h
Normal file
@@ -0,0 +1,37 @@
|
||||
#ifndef NETWORKING_H
|
||||
#define NETWORKING_H
|
||||
|
||||
#include <SDL2/SDL_net.h>
|
||||
#include <vector>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <chrono>
|
||||
#include "../Utility/env.h"
|
||||
#include "networking_client.h"
|
||||
#include "../Entities/player.h"
|
||||
#include "../Entities/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);
|
||||
struct PlayerInfo {
|
||||
int id;
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
std::vector<PlayerInfo> getAllPlayers();
|
||||
void sendPlayerListToNewClient(int clientSocket);
|
||||
|
||||
#endif //NETWORKING_H
|
||||
198
Network/networking_client.cpp
Normal file
198
Network/networking_client.cpp
Normal file
@@ -0,0 +1,198 @@
|
||||
#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;
|
||||
std::cout << "Return to menu..." << std::endl;
|
||||
eventHandler.triggerEvent("playerLost");
|
||||
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();
|
||||
}
|
||||
|
||||
void receivePlayerListFromServer(TCPsocket serverSocket) {
|
||||
// Exemple de structure de données pour un joueur
|
||||
struct PlayerInfo {
|
||||
int id;
|
||||
int x;
|
||||
int y;
|
||||
};
|
||||
|
||||
// Recevoir le message contenant la liste des joueurs
|
||||
std::string message = receiveMessage(serverSocket);
|
||||
if (message.empty()) {
|
||||
std::cerr << "Failed to receive player list" << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
std::istringstream iss(message);
|
||||
std::string token;
|
||||
std::getline(iss, token, ';'); // Lire "playerList"
|
||||
if (token != "playerList") {
|
||||
std::cerr << "Invalid message format" << std::endl;
|
||||
return;
|
||||
}
|
||||
|
||||
// Lire le nombre de joueurs
|
||||
std::getline(iss, token, ';');
|
||||
int playerCount = std::stoi(token);
|
||||
|
||||
// Lire les informations de chaque joueur
|
||||
for (int i = 0; i < playerCount; ++i) {
|
||||
std::getline(iss, token, ';');
|
||||
int playerId, x, y;
|
||||
sscanf(token.c_str(), "%d,%d,%d", &playerId, &x, &y);
|
||||
// Mettre à jour l'état du client avec les informations du joueur
|
||||
addPlayerToGame(playerId, x, y);
|
||||
}
|
||||
}
|
||||
|
||||
void addPlayerToGame(int playerId, int x, int y) {
|
||||
// Vérifiez si le joueur existe déjà
|
||||
auto it = std::find_if(players.begin(), players.end(), [playerId](const Player& player) {
|
||||
return player.getPlayerId() == playerId;
|
||||
});
|
||||
|
||||
if (it != players.end()) {
|
||||
// Si le joueur existe déjà, mettez à jour sa position
|
||||
it->updatePosition(x, y);
|
||||
} else {
|
||||
// Sinon, ajoutez un nouveau joueur
|
||||
players.emplace_back(Player(x, y, 5, renderer, playerId));
|
||||
}
|
||||
}
|
||||
28
Network/networking_client.h
Normal file
28
Network/networking_client.h
Normal file
@@ -0,0 +1,28 @@
|
||||
//
|
||||
// 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 "../Utility/env.h"
|
||||
#include "../Entities/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);
|
||||
void receivePlayerListFromServer(int serverSocket);
|
||||
void addPlayerToGame(int playerId, int x, int y);
|
||||
#endif //NETWORKING_CLIENT_H
|
||||
65
README.md
65
README.md
@@ -1 +1,64 @@
|
||||
# bloubloulespoissons
|
||||
# bloubloulespoissons
|
||||
Bloublou les poissons est un jeu de simulation de comportement de poisson en réseau ou bien en solo.
|
||||
|
||||
Le jeu est codé en C++ avec la librairie SDL2.
|
||||
|
||||
# 🌱 Branches en développement
|
||||
- `main` : La branche principale du projet
|
||||
- `WII-U` : La branche pour la version Wii-U du jeu
|
||||
- `SDL3-2.0` : La branche pour la version SDL3 du jeu
|
||||
|
||||
# 🚀 Installation et configuration
|
||||
## Prérequis
|
||||
- [SDL2](https://www.libsdl.org/download-2.0.php)
|
||||
- [SDL2_image](https://www.libsdl.org/projects/SDL_image/)
|
||||
- [SDL2_ttf](https://www.libsdl.org/projects/SDL_ttf/)
|
||||
- [SDL2_mixer](https://www.libsdl.org/projects/SDL_mixer/)
|
||||
- [SDL2_net](https://www.libsdl.org/projects/SDL_net/)
|
||||
- [CMake](https://cmake.org/download/)
|
||||
- [Git](https://git-scm.com/downloads)
|
||||
- [GCC](https://gcc.gnu.org/)
|
||||
- [Make](https://www.gnu.org/software/make/)
|
||||
|
||||
## Lancement avec la binaire
|
||||
1. Téléchargez la dernière version de l'application
|
||||
```bash
|
||||
https://github.com/BreizhHardware/bloubloulespoissons/releases
|
||||
```
|
||||
2. Executez le fichier .exe
|
||||
|
||||
3. Jouez
|
||||
|
||||
## Compilation et lancement
|
||||
1. Clonez le dépôt
|
||||
```bash
|
||||
git clone https://github.com/BreizhHardware/bloubloulespoissons.git
|
||||
cd bloubloulespoissons
|
||||
```
|
||||
2. Créez un dossier build
|
||||
```bash
|
||||
mkdir build
|
||||
cd build
|
||||
```
|
||||
3. Générez les fichiers de configuration
|
||||
```bash
|
||||
cmake ..
|
||||
```
|
||||
4. Compilez le projet
|
||||
```bash
|
||||
make -j
|
||||
```
|
||||
5. Lancez le jeu
|
||||
```bash
|
||||
./bloubloulespoissons
|
||||
```
|
||||
|
||||
# To do
|
||||
- [x] Voir les autres joueurs
|
||||
- [x] Id Incrémental pour les players
|
||||
- [x] Récupération des infos des champs de text pour le join
|
||||
- [X] Affichage de l'ip dans le champs d'host (fonctionnalité retiré)
|
||||
- [x] Requin adversaire
|
||||
- [x] Choix des musiques pour le jeux
|
||||
- [x] Pouvoir mute les musiques via la touche M
|
||||
- [x] Refactorer le code pour le rendre plus lisible
|
||||
|
||||
147
Utility/close.cpp
Normal file
147
Utility/close.cpp
Normal file
@@ -0,0 +1,147 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#include "close.h"
|
||||
|
||||
void handleQuitThread() {
|
||||
std::cout << "handleQuitThread..." << std::endl;
|
||||
while (game_running) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
||||
handleQuit();
|
||||
}
|
||||
std::cout << "handleQuitThread" << std::endl;
|
||||
}
|
||||
|
||||
void handleQuit() {
|
||||
SDL_Event event;
|
||||
const Uint8* keystate = SDL_GetKeyboardState(NULL);
|
||||
|
||||
while (SDL_PollEvent(&event)) {
|
||||
if (event.type == SDL_QUIT) {
|
||||
if (isPlayingOnline && isHost) {
|
||||
closeServer();
|
||||
}
|
||||
game_running = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (keystate[SDL_SCANCODE_ESCAPE]) {
|
||||
if (isPlayingOnline && isHost) {
|
||||
closeServer();
|
||||
}
|
||||
game_running = false;
|
||||
}
|
||||
|
||||
if (keystate[SDL_SCANCODE_M]) {
|
||||
soundMuted = !soundMuted;
|
||||
if (soundMuted) {
|
||||
Mix_Volume(-1, 0);
|
||||
Mix_VolumeMusic(0);
|
||||
} else {
|
||||
Mix_Volume(-1, MIX_MAX_VOLUME);
|
||||
Mix_VolumeMusic(MIX_MAX_VOLUME);
|
||||
}
|
||||
}
|
||||
|
||||
if (keystate[SDL_SCANCODE_F2]) {
|
||||
displayFPSFlag = !displayFPSFlag;
|
||||
}
|
||||
}
|
||||
|
||||
void cleanup() {
|
||||
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) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
if (renderer != nullptr) {
|
||||
SDL_DestroyRenderer(renderer);
|
||||
renderer = nullptr;
|
||||
}
|
||||
} catch (const std::exception& e) {
|
||||
std::cerr << "Exception caught for DestroyRenderer: " << e.what() << std::endl;
|
||||
}
|
||||
|
||||
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 {
|
||||
// if (backgroundMusic != nullptr) {
|
||||
// Mix_FreeMusic(backgroundMusic);
|
||||
// backgroundMusic = nullptr;
|
||||
// }
|
||||
// } catch (const std::exception& e) {
|
||||
// std::cerr << "Exception caught for FreeMusic: " << e.what() << std::endl;
|
||||
// }
|
||||
|
||||
// try {
|
||||
// if (menuMusic != nullptr) {
|
||||
// Mix_FreeMusic(menuMusic);
|
||||
// menuMusic = nullptr;
|
||||
// }
|
||||
// } catch (const std::exception& e) {
|
||||
// std::cerr << "Exception caught for FreeMusic (menuMusic): " << 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;
|
||||
}
|
||||
}
|
||||
21
Utility/close.h
Normal file
21
Utility/close.h
Normal file
@@ -0,0 +1,21 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#ifndef CLOSE_H
|
||||
#define CLOSE_H
|
||||
#include <SDL2/SDL.h>
|
||||
#include <SDL2/SDL_mixer.h>
|
||||
#include <SDL2/SDL_net.h>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include "env.h"
|
||||
#include "../Network/networking.h"
|
||||
|
||||
void cleanup();
|
||||
void handleQuit();
|
||||
void handleQuitThread();
|
||||
|
||||
#endif //CLOSE_H
|
||||
40
Utility/display.cpp
Normal file
40
Utility/display.cpp
Normal 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 == ¤tPlayer) 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
Utility/display.h
Normal file
17
Utility/display.h
Normal 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 "../Entities/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
|
||||
@@ -1,6 +1,6 @@
|
||||
#include "env.h"
|
||||
|
||||
#include <vector>
|
||||
#include "../Entities/player.h"
|
||||
#include "../Entities/fish.h"
|
||||
|
||||
int windowWidth = 1500;
|
||||
int windowHeight = 800;
|
||||
@@ -15,7 +15,31 @@ SDL_Renderer* renderer = nullptr;
|
||||
SDL_Window* window = nullptr;
|
||||
TTF_Font* font = nullptr;
|
||||
int fishCount = 0;
|
||||
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);
|
||||
EventHandler eventHandler;
|
||||
std::atomic<bool> soundMuted(false);
|
||||
SDL_Texture* playerTexture = nullptr;
|
||||
SDL_Texture* fishTextures[100];
|
||||
std::vector<Fish> school;
|
||||
MusicManager musicManager;
|
||||
std::atomic<bool> displayFPSFlag(true);
|
||||
|
||||
|
||||
void resetAll(){
|
||||
game_running = false;
|
||||
isPlayingOnline = false;
|
||||
messageThreadRunning = false;
|
||||
isHost = false;
|
||||
players.clear();
|
||||
players_server.clear();
|
||||
}
|
||||
|
||||
|
||||
bool initEnvironment(SDL_Renderer* renderer) {
|
||||
SDL_Surface* backgroundSurface = IMG_Load("../img/background.png");
|
||||
@@ -71,5 +95,12 @@ std::vector<SDL_Texture*> initTexture(SDL_Renderer* renderer) {
|
||||
}
|
||||
textures.push_back(SDL_CreateTextureFromSurface(renderer, rockSurface));
|
||||
SDL_FreeSurface(rockSurface);
|
||||
|
||||
//Load the coral texture
|
||||
SDL_Surface* coralSurface = IMG_Load("../img/coral.png");
|
||||
if (coralSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'image du Coral: " << IMG_GetError() << std::endl;
|
||||
}
|
||||
textures.push_back(SDL_CreateTextureFromSurface(renderer, coralSurface));
|
||||
return textures;
|
||||
}
|
||||
57
Utility/env.h
Normal file
57
Utility/env.h
Normal file
@@ -0,0 +1,57 @@
|
||||
#ifndef ENV_H
|
||||
#define ENV_H
|
||||
|
||||
#include <atomic>
|
||||
#include <SDL2/SDL.h>
|
||||
#include <SDL2/SDL_image.h>
|
||||
#include <SDL2/SDL_ttf.h>
|
||||
#include <SDL2/SDL_mixer.h>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <dirent.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include "music.h"
|
||||
#include "event.h"
|
||||
|
||||
class Player;
|
||||
|
||||
class Fish;
|
||||
|
||||
extern int windowWidth;
|
||||
extern int windowHeight;
|
||||
extern int playerBaseX;
|
||||
extern int playerBaseY;
|
||||
extern const int MARGIN_WIDTH;
|
||||
extern const int MARGIN_HEIGHT;
|
||||
extern int ENV_HEIGHT;
|
||||
extern int ENV_WIDTH;
|
||||
extern SDL_Texture* backgroundTexture;
|
||||
extern SDL_Renderer* renderer;
|
||||
extern SDL_Window* window;
|
||||
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;
|
||||
extern EventHandler eventHandler;
|
||||
extern std::atomic<bool> soundMuted;
|
||||
extern SDL_Texture* fishTextures[100];
|
||||
extern SDL_Texture* playerTexture;
|
||||
extern std::vector<Fish> school;
|
||||
extern MusicManager musicManager;
|
||||
extern std::atomic<bool> displayFPSFlag;
|
||||
|
||||
bool initEnvironment(SDL_Renderer* renderer);
|
||||
std::vector<SDL_Texture*> initTexture(SDL_Renderer* renderer);
|
||||
|
||||
void resetAll();
|
||||
|
||||
#endif // ENV_H
|
||||
34
Utility/event.h
Normal file
34
Utility/event.h
Normal file
@@ -0,0 +1,34 @@
|
||||
#ifndef EVENTHANDLER_H
|
||||
#define EVENTHANDLER_H
|
||||
|
||||
#include <functional>
|
||||
#include <unordered_map>
|
||||
#include <string>
|
||||
|
||||
class EventHandler {
|
||||
public:
|
||||
using EventCallback = std::function<void()>;
|
||||
|
||||
template <typename EventCallback, typename... Args>
|
||||
|
||||
void registerEvent(const std::string& eventName, EventCallback callback, Args&&... args) {
|
||||
|
||||
eventCallbacks[eventName] = [callback, ...args = std::forward<Args>(args)]() {
|
||||
|
||||
callback(args.get()...);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
void triggerEvent(const std::string& eventName) {
|
||||
if (eventCallbacks.find(eventName) != eventCallbacks.end()) {
|
||||
eventCallbacks[eventName]();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
std::unordered_map<std::string, EventCallback> eventCallbacks;
|
||||
};
|
||||
|
||||
#endif
|
||||
192
Utility/music.h
Normal file
192
Utility/music.h
Normal file
@@ -0,0 +1,192 @@
|
||||
#ifndef MUSIC_H
|
||||
#define MUSIC_H
|
||||
|
||||
#include <SDL2/SDL_mixer.h>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
enum class AudioType {
|
||||
MUSIC,
|
||||
SOUND_EFFECT
|
||||
};
|
||||
|
||||
enum AudioChannel {
|
||||
MUSIC_CHANNEL = 0,
|
||||
SOUND_CHANNEL = 1
|
||||
};
|
||||
|
||||
struct Audio {
|
||||
Mix_Music* music;
|
||||
Mix_Chunk* sound;
|
||||
};
|
||||
|
||||
class Music {
|
||||
private:
|
||||
AudioType type;
|
||||
std::vector<Audio> audio;
|
||||
std::string path;
|
||||
std::string name;
|
||||
AudioChannel channel;
|
||||
|
||||
public:
|
||||
Music(std::string filePath, AudioType audio_type){
|
||||
name = getNameFromPath(filePath);
|
||||
path = filePath;
|
||||
type = audio_type;
|
||||
std::cout << "Loading " << name << " from " << path << std::endl;
|
||||
if(type == AudioType::MUSIC){
|
||||
channel = MUSIC_CHANNEL;
|
||||
Mix_Music* music = Mix_LoadMUS(filePath.c_str());
|
||||
Audio sss;
|
||||
sss.music = music;
|
||||
if(music == nullptr){
|
||||
std::cerr << "Error loading music: " << Mix_GetError() << std::endl;
|
||||
}else{
|
||||
audio.push_back(sss);
|
||||
}
|
||||
}else if (type == AudioType::SOUND_EFFECT)
|
||||
{
|
||||
channel = SOUND_CHANNEL;
|
||||
Mix_Chunk* sound = Mix_LoadWAV(filePath.c_str());
|
||||
Audio sss;
|
||||
sss.sound = sound;
|
||||
if(sound == nullptr){
|
||||
std::cerr << "Error loading sound effect: " << Mix_GetError() << std::endl;
|
||||
}else{
|
||||
audio.push_back(sss);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ~Music(){
|
||||
// if(type == AudioType::MUSIC){
|
||||
// Mix_FreeMusic(audio[0].music);
|
||||
// }else if (type == AudioType::SOUND_EFFECT)
|
||||
// {
|
||||
// Mix_FreeChunk(audio[0].sound);
|
||||
// }
|
||||
// }
|
||||
|
||||
std::string getName(){
|
||||
return name;
|
||||
}
|
||||
|
||||
std::string getNameFromPath(std::string path){
|
||||
std::string name = path.substr(path.find_last_of("/\\") + 1);
|
||||
name = name.substr(0, name.find_last_of("."));
|
||||
std::cout << "Name: " << name << std::endl;
|
||||
return name;
|
||||
}
|
||||
|
||||
void play(){
|
||||
if(type == AudioType::MUSIC){
|
||||
Mix_HaltChannel(channel);
|
||||
Mix_PlayMusic(audio[0].music, channel);
|
||||
}else if (type == AudioType::SOUND_EFFECT)
|
||||
{
|
||||
Mix_HaltChannel(channel);
|
||||
Mix_PlayChannel(channel, audio[0].sound, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void stop(){
|
||||
if(type == AudioType::MUSIC){
|
||||
Mix_HaltChannel(channel);
|
||||
}else if (type == AudioType::SOUND_EFFECT)
|
||||
{
|
||||
Mix_HaltChannel(channel);
|
||||
}
|
||||
}
|
||||
|
||||
void pause(){
|
||||
if(type == AudioType::MUSIC){
|
||||
Mix_PauseMusic();
|
||||
}else if (type == AudioType::SOUND_EFFECT)
|
||||
{
|
||||
Mix_Pause(channel);
|
||||
}
|
||||
}
|
||||
|
||||
void resume(){
|
||||
if(type == AudioType::MUSIC){
|
||||
Mix_ResumeMusic();
|
||||
}else if (type == AudioType::SOUND_EFFECT)
|
||||
{
|
||||
Mix_Resume(channel);
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
class MusicManager {
|
||||
private:
|
||||
std::vector<Music> musicList;
|
||||
int volume = MIX_MAX_VOLUME;
|
||||
public:
|
||||
|
||||
MusicManager(){
|
||||
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0){
|
||||
std::cerr << "Error initializing SDL_mixer: " << Mix_GetError() << std::endl;
|
||||
}
|
||||
Mix_Volume(-1, volume);
|
||||
Mix_VolumeMusic(volume);
|
||||
}
|
||||
|
||||
~MusicManager(){
|
||||
for(Music music : musicList){
|
||||
music.stop();
|
||||
}
|
||||
Mix_CloseAudio();
|
||||
}
|
||||
|
||||
void addMusic(std::string filePath, AudioType audio_type){
|
||||
Music music(filePath, audio_type);
|
||||
musicList.push_back(music);
|
||||
}
|
||||
|
||||
void playMusic(std::string name){
|
||||
for(Music music : musicList){
|
||||
if(music.getName() == name){
|
||||
music.play();
|
||||
std::cout << "Started playing " << name << std::endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void stopMusic(std::string name){
|
||||
for(Music music : musicList){
|
||||
if(music.getName() == name){
|
||||
music.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void resumeMusic(std::string name){
|
||||
for(Music music : musicList){
|
||||
if(music.getName() == name){
|
||||
music.resume();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setVolume(int volume){
|
||||
this->volume = volume;
|
||||
Mix_Volume(-1, volume);
|
||||
Mix_VolumeMusic(volume);
|
||||
}
|
||||
|
||||
void pauseMusic(std::string name){
|
||||
for(Music music : musicList){
|
||||
if(music.getName() == name){
|
||||
music.pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
253
Utility/utility.cpp
Normal file
253
Utility/utility.cpp
Normal file
@@ -0,0 +1,253 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#include "utility.h"
|
||||
|
||||
std::mutex mtx;
|
||||
std::vector<ThreadInfo> threadInfos;
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void displayFPS(SDL_Renderer* renderer, TTF_Font* font, int fps) {
|
||||
std::string fpsText = "FPS: " + std::to_string(fps);
|
||||
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};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
}
|
||||
|
||||
void displayPlayerCoord(SDL_Renderer* renderer, TTF_Font* font, int playerX, int playerY) {
|
||||
Camera& camera = Camera::getInstance();
|
||||
int cameraX = camera.getX();
|
||||
int cameraY = camera.getY();
|
||||
|
||||
std::string coordText = "Camera: (" + std::to_string(cameraX) + ", " + std::to_string(cameraY) + ")";
|
||||
std::string coordText2 = "Player: (" + std::to_string(playerX) + ", " + std::to_string(playerY) + ")";
|
||||
SDL_Color textColor = {0, 255, 0};
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font, coordText.c_str(), textColor);
|
||||
SDL_Surface* textSurface2 = TTF_RenderText_Solid(font, coordText2.c_str(), textColor);
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_Texture* textTexture2 = SDL_CreateTextureFromSurface(renderer, textSurface2);
|
||||
|
||||
SDL_Rect textRect = {10, 30, textSurface->w, textSurface->h};
|
||||
SDL_Rect textRect2 = {10, 50, textSurface2->w, textSurface2->h};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
|
||||
SDL_RenderCopy(renderer, textTexture2, nullptr, &textRect2);
|
||||
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_FreeSurface(textSurface2);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
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;
|
||||
}
|
||||
|
||||
Mix_AllocateChannels(16);
|
||||
|
||||
// Charger la musique du menu
|
||||
// menuMusic = Mix_LoadMUS("../sounds/Menu.wav");
|
||||
// if (menuMusic == nullptr) {
|
||||
// std::cerr << "Erreur de chargement de la musique du menu: " << Mix_GetError() << std::endl;
|
||||
// return false;
|
||||
// }
|
||||
|
||||
window = SDL_CreateWindow("BloubBloub les poissons",
|
||||
SDL_WINDOWPOS_CENTERED,
|
||||
SDL_WINDOWPOS_CENTERED,
|
||||
windowWidth, windowHeight,
|
||||
SDL_WINDOW_SHOWN);
|
||||
if (window == nullptr) {
|
||||
std::cerr << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
SDL_Surface* iconSurface = IMG_Load("../img/logo.png");
|
||||
if(iconSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'icône: " << IMG_GetError() << std::endl;
|
||||
} else {
|
||||
SDL_SetWindowIcon(window, iconSurface);
|
||||
SDL_FreeSurface(iconSurface);
|
||||
}
|
||||
|
||||
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
||||
if (renderer == nullptr) {
|
||||
std::cerr << "Erreur de création du renderer: " << SDL_GetError() << std::endl;
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_Quit();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
|
||||
std::cerr << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TTF_Init() == -1) {
|
||||
std::cerr << "SDL_ttf could not initialize! SDL_ttf Error: " << TTF_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!initEnvironment(renderer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < fishCount; ++i) {
|
||||
std::string fishTexturePath = "../img/fish/fish" + std::to_string(i) + ".png";
|
||||
SDL_Surface* fishSurface = IMG_Load(fishTexturePath.c_str());
|
||||
if (fishSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'image du poisson: " << IMG_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
fishTextures[i] = SDL_CreateTextureFromSurface(renderer, fishSurface);
|
||||
if (fishTextures[i] == nullptr) {
|
||||
std::cerr << "Erreur de création de la texture du poisson: " << SDL_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
SDL_FreeSurface(fishSurface);
|
||||
}
|
||||
|
||||
texturesVector = initTexture(renderer);
|
||||
return true;
|
||||
}
|
||||
|
||||
void updateFishRange(std::vector<Fish>& school, int start, int end){
|
||||
while (game_running) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(16));
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
Fish::insertionSort(school);
|
||||
}
|
||||
for (int i = start; i < end; ++i) {
|
||||
school[i].cycle(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void playerMovementThread(Player& player) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
void updateShark(Shark &shark) {
|
||||
while (game_running) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(16));
|
||||
shark.cycle();
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
const Uint32 currentTime = SDL_GetTicks64();
|
||||
frameCount++;
|
||||
if (currentTime - lastTime >= 1000) {
|
||||
fps = frameCount;
|
||||
frameCount = 0;
|
||||
lastTime = currentTime;
|
||||
}
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
||||
SDL_RenderClear(renderer);
|
||||
|
||||
Camera& camera = Camera::getInstance();
|
||||
SDL_Rect backgroundRect = { -camera.getX(), -camera.getY(), ENV_WIDTH, ENV_HEIGHT };
|
||||
SDL_RenderCopy(renderer, backgroundTexture, nullptr, &backgroundRect);
|
||||
|
||||
for (const auto& kelp : kelps) {
|
||||
kelp.draw(renderer);
|
||||
}
|
||||
|
||||
for (const auto& rock : rocks) {
|
||||
rock.draw(renderer);
|
||||
}
|
||||
|
||||
for (const auto& coral : corals) {
|
||||
coral.draw(renderer);
|
||||
}
|
||||
|
||||
for (Fish& fish : school) {
|
||||
fish.draw(renderer);
|
||||
}
|
||||
|
||||
for (auto& player : players) {
|
||||
player.draw(renderer);
|
||||
}
|
||||
|
||||
if (isPlayingOnline) {
|
||||
displayNearbyPlayers(renderer, font, players[0], players_server, 500);
|
||||
}
|
||||
|
||||
shark.draw(renderer);
|
||||
|
||||
if (displayFPSFlag) {
|
||||
displayFPS(renderer, font, fps);
|
||||
}
|
||||
|
||||
SDL_RenderPresent(renderer);
|
||||
}
|
||||
|
||||
void handleClientMessages(Player& player) {
|
||||
std::cout << "messageThread started..." << std::endl;
|
||||
while (messageThreadRunning) {
|
||||
player.handleClientMessages();
|
||||
}
|
||||
std::cout << "messageThread ended" << std::endl;
|
||||
}
|
||||
81
Utility/utility.h
Normal file
81
Utility/utility.h
Normal file
@@ -0,0 +1,81 @@
|
||||
//
|
||||
// Created by BreizhHardware on 18/12/2024.
|
||||
//
|
||||
|
||||
#ifndef UTILITY_H
|
||||
#define UTILITY_H
|
||||
#include <SDL2/SDL.h>
|
||||
#include <SDL2/SDL_ttf.h>
|
||||
#include <SDL2/SDL_image.h>
|
||||
#include <SDL2/SDL_mixer.h>
|
||||
#include <SDL2/SDL_net.h>
|
||||
#include <vector>
|
||||
#include <thread>
|
||||
#include <mutex>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include "env.h"
|
||||
#include "../Game/camera.h"
|
||||
#include "../Entities/fish.h"
|
||||
#include "../Entities/player.h"
|
||||
#include "../Entities/shark.h"
|
||||
#include "../Game/decors.h"
|
||||
#include "../Utility/display.h"
|
||||
|
||||
extern std::mutex mtx;
|
||||
|
||||
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 checkThreads();
|
||||
bool initSDL();
|
||||
struct ThreadInfo {
|
||||
std::thread::id id;
|
||||
std::string functionName;
|
||||
bool isRunning;
|
||||
};
|
||||
extern std::vector<ThreadInfo> threadInfos;
|
||||
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 updateFishRange(std::vector<Fish>& school, int start, int end);
|
||||
void playerMovementThread(Player& player);
|
||||
void updateShark(Shark &shark);
|
||||
void renderScene(std::vector<Player>& players, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks, const std::vector<Coral>& corals,Shark& shark );
|
||||
void handleClientMessages(Player& player);
|
||||
#endif //UTILITY_H
|
||||
32
env.h
32
env.h
@@ -1,32 +0,0 @@
|
||||
#ifndef ENV_H
|
||||
#define ENV_H
|
||||
|
||||
#include <SDL.h>
|
||||
#include <SDL_image.h>
|
||||
#include <SDL_ttf.h>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
#include <dirent.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
extern int windowWidth;
|
||||
extern int windowHeight;
|
||||
extern int playerBaseX;
|
||||
extern int playerBaseY;
|
||||
extern const int MARGIN_WIDTH;
|
||||
extern const int MARGIN_HEIGHT;
|
||||
extern int ENV_HEIGHT;
|
||||
extern int ENV_WIDTH;
|
||||
extern SDL_Texture* backgroundTexture;
|
||||
extern SDL_Renderer* renderer;
|
||||
extern SDL_Window* window;
|
||||
extern TTF_Font* font;
|
||||
extern int fishCount;
|
||||
extern std::vector<SDL_Texture*> texturesVector;
|
||||
|
||||
bool initEnvironment(SDL_Renderer* renderer);
|
||||
std::vector<SDL_Texture*> initTexture(SDL_Renderer* renderer);
|
||||
|
||||
#endif // ENV_H
|
||||
121
fish.cpp
121
fish.cpp
@@ -1,121 +0,0 @@
|
||||
#include "fish.h"
|
||||
|
||||
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
|
||||
SDL_Point points[4];
|
||||
|
||||
if (vx == 0 && vy == 0) return;
|
||||
|
||||
float angle = atan2(vy, vx);
|
||||
points[0] = {x + static_cast<int>(arrowLength * cos(angle)), y + static_cast<int>(arrowLength * sin(angle))};
|
||||
points[1] = {
|
||||
x + static_cast<int>(arrowWidth * cos(angle + M_PI / 6)),
|
||||
y + static_cast<int>(arrowWidth * sin(angle + M_PI / 6))
|
||||
};
|
||||
points[2] = {
|
||||
x + static_cast<int>(arrowWidth * cos(angle - M_PI / 6)),
|
||||
y + static_cast<int>(arrowWidth * sin(angle - M_PI / 6))
|
||||
};
|
||||
points[3] = points[0];
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); // Vert
|
||||
SDL_RenderDrawLines(renderer, points, 4);
|
||||
}
|
||||
|
||||
void Fish::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, 255, 0, 0, 255); // Red
|
||||
SDL_RenderFillRect(renderer, &rect);
|
||||
}
|
||||
//drawArrow(renderer, x + width / 2, y + height / 2, vx, vy);
|
||||
}
|
||||
|
||||
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;
|
||||
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) {
|
||||
const float other_x = schoolIt.getX();
|
||||
const float other_y = schoolIt.getY();
|
||||
const float other_vx = schoolIt.getVx();
|
||||
const float other_vy = schoolIt.getVy();
|
||||
float dx = x - other_x;
|
||||
float dy = y - other_y;
|
||||
if (abs(dx) < VISUAL_RANGE && abs(dy) < VISUAL_RANGE) {
|
||||
if ((dx * dx + dy * dy) < PROTECTED_RANGE * PROTECTED_RANGE) {
|
||||
close_dx += x - other_x;
|
||||
close_dy += y - other_y;
|
||||
} else if ((dx * dx + dy * dy) < VISUAL_RANGE * VISUAL_RANGE) {
|
||||
xpos_avg += other_x;
|
||||
ypos_avg += other_y;
|
||||
xvel_avg += other_vx;
|
||||
yvel_avg += other_vy;
|
||||
neighboring_boids++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (neighboring_boids > 0) {
|
||||
xpos_avg /= neighboring_boids;
|
||||
ypos_avg /= neighboring_boids;
|
||||
xvel_avg /= neighboring_boids;
|
||||
yvel_avg /= neighboring_boids;
|
||||
vx += (xpos_avg - x) * CENTERING_FACTOR + (xvel_avg - vx) * MATCHING_FACTOR;
|
||||
vy += (ypos_avg - y) * CENTERING_FACTOR + (yvel_avg - vy) * MATCHING_FACTOR;
|
||||
}
|
||||
vx += close_dx * AVOIDANCE_FORCE;
|
||||
vy += close_dy * AVOIDANCE_FORCE;
|
||||
|
||||
if ( y <= 0) {
|
||||
vy += TURN_FACTOR;
|
||||
}
|
||||
if ( y >= (ENV_WIDTH - MARGIN_HEIGHT)) {
|
||||
vy -= TURN_FACTOR;
|
||||
}
|
||||
if ( x <= 0) {
|
||||
vx += TURN_FACTOR;
|
||||
}
|
||||
if ( x >= (ENV_WIDTH - MARGIN_WIDTH)) {
|
||||
vx -= TURN_FACTOR;
|
||||
}
|
||||
|
||||
if (biasdir == 1) {
|
||||
vx = (1 - BIASVALUE) * vx + (BIASVALUE * 1);
|
||||
}else if (biasdir == 0){
|
||||
vx = (1 - BIASVALUE) * vx + (BIASVALUE * -1);
|
||||
}
|
||||
|
||||
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;
|
||||
//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;
|
||||
}
|
||||
}
|
||||
|
||||
BIN
img/coral.png
Normal file
BIN
img/coral.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 299 KiB |
BIN
img/logo.ico
Normal file
BIN
img/logo.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 116 KiB |
BIN
img/logo.png
Normal file
BIN
img/logo.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
BIN
img/menu/background.png
Normal file
BIN
img/menu/background.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 306 KiB |
BIN
img/perdu.png
Normal file
BIN
img/perdu.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
6461
img/shark.pdn
Normal file
6461
img/shark.pdn
Normal file
File diff suppressed because one or more lines are too long
BIN
img/shark.png
Normal file
BIN
img/shark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 43 KiB |
435
main.cpp
435
main.cpp
@@ -1,289 +1,224 @@
|
||||
#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 "env.h"
|
||||
#include "player.h"
|
||||
#include "Entities/fish.h"
|
||||
#include "Game/decors.h"
|
||||
#include "Game/camera.h"
|
||||
#include "Utility/display.h"
|
||||
#include "Utility/env.h"
|
||||
#include "Utility/utility.h"
|
||||
#include "Entities/player.h"
|
||||
#include "Game/menu.h"
|
||||
#include "Network/networking.h"
|
||||
#include "Network/networking_client.h"
|
||||
#include "Entities/shark.h"
|
||||
#include "Utility/event.h"
|
||||
#include "Utility/close.h"
|
||||
#include "Game/launchGameSolo.h"
|
||||
#include "Game/launchGameMulti.h"
|
||||
|
||||
std::mutex mtx;
|
||||
std::atomic<bool> running(true);
|
||||
|
||||
SDL_Texture* playerTexture = nullptr;
|
||||
SDL_Texture* fishTextures[100]; // Adjust the size as needed
|
||||
std::vector<Fish> school;
|
||||
#include <system_error>
|
||||
|
||||
bool initSDL();
|
||||
void handleQuit();
|
||||
void renderScene(Player player, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks);
|
||||
void cleanup();
|
||||
std::atomic<bool> menuRunning(true);
|
||||
|
||||
void drawGradientBackground(SDL_Renderer* renderer) {
|
||||
for (int y = 0; y < ENV_HEIGHT; y++) {
|
||||
Uint8 blue = static_cast<Uint8>(255 * (1.0 - static_cast<float>(y) / ENV_HEIGHT));
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, blue, 255);
|
||||
SDL_RenderDrawLine(renderer, 0, y, ENV_WIDTH, y);
|
||||
std::mutex coutMutex;
|
||||
std::vector<Player> players;
|
||||
std::vector<Player> players_server;
|
||||
|
||||
void HandleMenuClick(Menu& menu);
|
||||
|
||||
void HandleMenuClick(Menu& menu){
|
||||
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 drawGridBackground(SDL_Renderer* renderer) {
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 255, 255);
|
||||
void onPlayerLost(Menu &menu){
|
||||
//Affiche drawLost par dessus le jeu
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
||||
SDL_RenderClear(renderer);
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
|
||||
|
||||
for (int y = 0; y < ENV_HEIGHT; y += 50) {
|
||||
SDL_RenderDrawLine(renderer, 0, y, ENV_WIDTH, y);
|
||||
std::string yText = std::to_string(y);
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font, yText.c_str(), {255, 255, 255});
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_Rect textRect = {0, y, textSurface->w, textSurface->h};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
}
|
||||
|
||||
for (int x = 0; x < ENV_WIDTH; x += 50) {
|
||||
SDL_RenderDrawLine(renderer, x, 0, x, ENV_HEIGHT);
|
||||
std::string xText = std::to_string(x);
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font, xText.c_str(), {255, 255, 255});
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_Rect textRect = {x, 0, textSurface->w, textSurface->h};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
}
|
||||
}
|
||||
|
||||
void updateFishRange(std::vector<Fish>& school, int start, int end){
|
||||
while (running) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(16));
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
for (int i = start; i < end; ++i) {
|
||||
school[i].cycle();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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_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};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
}
|
||||
|
||||
void displayPlayerCoord(SDL_Renderer* renderer, TTF_Font* font, int playerX, int playerY) {
|
||||
Camera& camera = Camera::getInstance();
|
||||
int cameraX = camera.getX();
|
||||
int cameraY = camera.getY();
|
||||
|
||||
std::string coordText = "Camera: (" + std::to_string(cameraX) + ", " + std::to_string(cameraY) + ")";
|
||||
std::string coordText2 = "Player: (" + std::to_string(playerX) + ", " + std::to_string(playerY) + ")";
|
||||
SDL_Color textColor = {0, 255, 0};
|
||||
SDL_Surface* textSurface = TTF_RenderText_Solid(font, coordText.c_str(), textColor);
|
||||
SDL_Surface* textSurface2 = TTF_RenderText_Solid(font, coordText2.c_str(), textColor);
|
||||
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
|
||||
SDL_Texture* textTexture2 = SDL_CreateTextureFromSurface(renderer, textSurface2);
|
||||
|
||||
SDL_Rect textRect = {10, 10, textSurface->w, textSurface->h};
|
||||
SDL_Rect textRect2 = {10, 30, textSurface2->w, textSurface2->h};
|
||||
SDL_RenderCopy(renderer, textTexture, nullptr, &textRect);
|
||||
SDL_RenderCopy(renderer, textTexture2, nullptr, &textRect2);
|
||||
|
||||
SDL_FreeSurface(textSurface);
|
||||
SDL_FreeSurface(textSurface2);
|
||||
SDL_DestroyTexture(textTexture);
|
||||
SDL_DestroyTexture(textTexture2);
|
||||
}
|
||||
|
||||
bool initSDL() {
|
||||
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
|
||||
std::cerr << "SDL could not initialize! SDL_Error: " << SDL_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
window = SDL_CreateWindow("BloubBloub les poissons",
|
||||
SDL_WINDOWPOS_CENTERED,
|
||||
SDL_WINDOWPOS_CENTERED,
|
||||
windowWidth, windowHeight,
|
||||
SDL_WINDOW_SHOWN);
|
||||
if (window == nullptr) {
|
||||
std::cerr << "Window could not be created! SDL_Error: " << SDL_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
SDL_Surface* iconSurface = IMG_Load("../img/mory.png");
|
||||
if(iconSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'icône: " << IMG_GetError() << std::endl;
|
||||
} else {
|
||||
SDL_SetWindowIcon(window, iconSurface);
|
||||
SDL_FreeSurface(iconSurface);
|
||||
}
|
||||
|
||||
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
||||
if (renderer == nullptr) {
|
||||
std::cerr << "Erreur de création du renderer: " << SDL_GetError() << std::endl;
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_Quit();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!(IMG_Init(IMG_INIT_PNG) & IMG_INIT_PNG)) {
|
||||
std::cerr << "SDL_image could not initialize! SDL_image Error: " << IMG_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (TTF_Init() == -1) {
|
||||
std::cerr << "SDL_ttf could not initialize! SDL_ttf Error: " << TTF_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!initEnvironment(renderer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < fishCount; ++i) {
|
||||
std::string fishTexturePath = "../img/fish/fish" + std::to_string(i) + ".png";
|
||||
SDL_Surface* fishSurface = IMG_Load(fishTexturePath.c_str());
|
||||
if (fishSurface == nullptr) {
|
||||
std::cerr << "Erreur de chargement de l'image du poisson: " << IMG_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
fishTextures[i] = SDL_CreateTextureFromSurface(renderer, fishSurface);
|
||||
if (fishTextures[i] == nullptr) {
|
||||
std::cerr << "Erreur de création de la texture du poisson: " << SDL_GetError() << std::endl;
|
||||
return false;
|
||||
}
|
||||
SDL_FreeSurface(fishSurface);
|
||||
}
|
||||
|
||||
texturesVector = initTexture(renderer);
|
||||
return true;
|
||||
menu.drawLost(renderer);
|
||||
SDL_RenderPresent(renderer);
|
||||
musicManager.playMusic("death");
|
||||
std::this_thread::sleep_for(std::chrono::seconds(8));
|
||||
menuRunning = true;
|
||||
menu.changePage("Main");
|
||||
musicManager.playMusic("Menu");
|
||||
menu.show();
|
||||
resetAll();
|
||||
}
|
||||
|
||||
int main(int argc, char* args[]) {
|
||||
|
||||
SDL_SetHint(SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR, "0");
|
||||
|
||||
if (!initSDL()) {
|
||||
std::cerr << "Failed to initialize!" << std::endl;
|
||||
return -1;
|
||||
}
|
||||
|
||||
std::vector<Kelp> kelps;
|
||||
std::vector<Rock> rocks;
|
||||
generateProceduralDecorations(kelps, rocks, ENV_HEIGHT, ENV_WIDTH, renderer);
|
||||
|
||||
for (int i = 0; i < 1000; ++i) {
|
||||
school.emplace_back(Fish(rand() % ENV_WIDTH, rand() % ENV_HEIGHT, 0.1, 0.1, school, i, 50, 50, renderer, rand() % 2 == 0 ? 1 : 0, fishTextures[rand() % fishCount]));
|
||||
Menu menu(renderer);
|
||||
menu.addPage("Main");
|
||||
menu.addPage("Multi");
|
||||
menu.addPage("Multi-Join");
|
||||
menu.changePage("Main");
|
||||
|
||||
|
||||
eventHandler.registerEvent("playerLost", onPlayerLost, 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.addImage("Main", (windowWidth/2) - 100, 150, 200, 200, "../img/logo.png");
|
||||
|
||||
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;
|
||||
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(0, nullptr);
|
||||
|
||||
});
|
||||
|
||||
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](){
|
||||
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](){
|
||||
menu.changePage("Multi-Join");
|
||||
});
|
||||
|
||||
// menu.addButton("Multi", (windowWidth/2) - 100, windowHeight/2 - 25, 200, 50, "Retour", 1024, [&menu](){
|
||||
// menu.changePage("Main");
|
||||
// });
|
||||
|
||||
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-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-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, "");
|
||||
}
|
||||
std::cout << "Thread: " << std::thread::hardware_concurrency() << std::endl;
|
||||
std::vector<std::thread> threads;
|
||||
int fishPerThread = school.size() / std::thread::hardware_concurrency();
|
||||
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())));
|
||||
}
|
||||
freopen("CON", "w", stdout);
|
||||
freopen("CON", "w", stderr);
|
||||
|
||||
Player player = Player(windowWidth / 2, windowHeight / 2, 5, renderer);
|
||||
|
||||
//menu.addButton((windowWidth/2) - 100, (windowHeight/2 + 25) + 50, 200, 50, "Multi", 1024);
|
||||
|
||||
// menuMusic = Mix_LoadMUS("../sounds/Menu.wav");
|
||||
// if (menuMusic != nullptr) {
|
||||
// Mix_VolumeMusic(MIX_MAX_VOLUME / 4);
|
||||
// if (Mix_PlayMusic(menuMusic, -1) == -1) {
|
||||
// std::cerr << "Erreur de lecture de la musique du menu: " << Mix_GetError() << std::endl;
|
||||
// }
|
||||
// }
|
||||
|
||||
musicManager.addMusic("../sounds/Menu.wav", AudioType::MUSIC);
|
||||
musicManager.addMusic("../sounds/Playing.wav", AudioType::MUSIC);
|
||||
musicManager.addMusic("../sounds/death.wav", AudioType::SOUND_EFFECT);
|
||||
musicManager.addMusic("../sounds/Shark-approching.wav", AudioType::SOUND_EFFECT);
|
||||
musicManager.addMusic("../sounds/shark.wav", AudioType::SOUND_EFFECT);
|
||||
|
||||
musicManager.playMusic("Menu");
|
||||
|
||||
while (running) {
|
||||
player.handlePlayerMovement(ENV_WIDTH, ENV_HEIGHT, windowWidth, windowHeight);
|
||||
|
||||
handleQuit();
|
||||
renderScene(player, kelps, rocks);
|
||||
SDL_Delay(10);
|
||||
}
|
||||
running = false;
|
||||
for (auto& thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
cleanup();
|
||||
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 (menuRunning){
|
||||
if (menu.isShown()) {
|
||||
menu.draw(renderer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (keystate[SDL_SCANCODE_ESCAPE]) {
|
||||
running = false;
|
||||
std::cout << "Check Threads 1" << std::endl;
|
||||
checkThreads();
|
||||
try {
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
void renderScene(Player player, const std::vector<Kelp>& kelps, const std::vector<Rock>& rocks) {
|
||||
static Uint32 lastTime = 0;
|
||||
static int frameCount = 0;
|
||||
static int fps = 0;
|
||||
|
||||
Uint32 currentTime = SDL_GetTicks();
|
||||
frameCount++;
|
||||
if (currentTime - lastTime >= 1000) {
|
||||
fps = frameCount;
|
||||
frameCount = 0;
|
||||
lastTime = currentTime;
|
||||
}
|
||||
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
||||
SDL_RenderClear(renderer);
|
||||
|
||||
Camera& camera = Camera::getInstance();
|
||||
SDL_Rect backgroundRect = { -camera.getX(), -camera.getY(), ENV_WIDTH, ENV_HEIGHT };
|
||||
SDL_RenderCopy(renderer, backgroundTexture, nullptr, &backgroundRect);
|
||||
|
||||
for (const auto& kelp : kelps) {
|
||||
kelp.draw(renderer);
|
||||
}
|
||||
|
||||
for (const auto& rock : rocks) {
|
||||
rock.draw(renderer);
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(mtx);
|
||||
for (auto& fish : school) {
|
||||
fish.draw(renderer);
|
||||
}
|
||||
|
||||
player.draw(renderer);
|
||||
|
||||
displayFPS(renderer, font, fps);
|
||||
int playerX, playerY;
|
||||
std::tie(playerX, playerY) = player.getPlayerPos();
|
||||
displayPlayerCoord(renderer, font, playerX, playerY);
|
||||
|
||||
SDL_RenderPresent(renderer);
|
||||
}
|
||||
|
||||
void cleanup() {
|
||||
TTF_CloseFont(font);
|
||||
TTF_Quit();
|
||||
SDL_DestroyTexture(backgroundTexture);
|
||||
for (int i = 0; i < fishCount; ++i) {
|
||||
SDL_DestroyTexture(fishTextures[i]);
|
||||
}
|
||||
if (renderer != nullptr) {
|
||||
SDL_DestroyRenderer(renderer);
|
||||
}
|
||||
if (window != nullptr) {
|
||||
SDL_DestroyWindow(window);
|
||||
}
|
||||
IMG_Quit();
|
||||
SDL_Quit();
|
||||
}
|
||||
114
player.cpp
114
player.cpp
@@ -1,114 +0,0 @@
|
||||
#include "player.h"
|
||||
#include <tuple>
|
||||
#include "camera.h"
|
||||
|
||||
void Player::updatePlayerPos(int x, int y) {
|
||||
this->x = x;
|
||||
this->y = y;
|
||||
this->playerPosForRender.x = x;
|
||||
this->playerPosForRender.y = y;
|
||||
};
|
||||
|
||||
void Player::updatePlayerSpeed(int playerSpeed) {
|
||||
this->playerSpeed = playerSpeed;
|
||||
};
|
||||
|
||||
std::tuple<int, int> Player::getPlayerPos() {
|
||||
return std::make_tuple(this->x, this->y);
|
||||
};
|
||||
|
||||
int Player::getPlayerSpeed() {
|
||||
return playerSpeed;
|
||||
};
|
||||
|
||||
|
||||
void Player::draw(SDL_Renderer* renderer) {
|
||||
switch (this->ticks) {
|
||||
case 0:
|
||||
this->currentSprite = PLAYER_SPRITE_1;
|
||||
break;
|
||||
case 5:
|
||||
this->currentSprite = PLAYER_SPRITE_2;
|
||||
break;
|
||||
case 8:
|
||||
this->currentSprite = PLAYER_SPRITE_3;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (this->ticks >= 8) {
|
||||
this->ticks = 0;
|
||||
} else {
|
||||
this->ticks++;
|
||||
}
|
||||
|
||||
SDL_RenderCopyEx(renderer, this->playerTexture, &this->playerRect[this->currentSprite], &this->playerPosForRender, 0, nullptr, this->currentFlip);
|
||||
};
|
||||
|
||||
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;
|
||||
int tempY = this->y;
|
||||
int speed = this->playerSpeed;
|
||||
|
||||
//Press left shift to increase speed MAIS C'EST BUG !!!!!!!!!!!!!
|
||||
if (keystate[SDL_SCANCODE_LSHIFT]) {
|
||||
speed = this->playerSpeed * 2;
|
||||
}
|
||||
|
||||
if (keystate[SDL_SCANCODE_W]) {
|
||||
//std::cout << "PlayerY: " << playerY << " Camera: " << camera.getY() << " ENV_HEIGHT: " << ENV_HEIGHT << " windowHeight: " << windowHeight << " playerBaseY: " << playerBaseY << std::endl;
|
||||
if (camera.getY() > 0 && tempY == this->playerBaseY) {
|
||||
camera.move(0, -speed);
|
||||
}else if (tempY > 0) {
|
||||
tempY -= speed;
|
||||
}
|
||||
}
|
||||
if (keystate[SDL_SCANCODE_S]) {
|
||||
// std::cout << "PlayerY: " << playerY << " Camera: " << camera.getY() << " ENV_HEIGHT: " << ENV_HEIGHT << " windowHeight: " << windowHeight << " playerBaseY: " << playerBaseY << std::endl;
|
||||
|
||||
if ((camera.getY() < ENV_HEIGHT-windowHeight) && (tempY == this->playerBaseY)) {
|
||||
camera.move(0, speed);
|
||||
}else if (tempY < windowHeight-PLAYER_SIZE_Y) {
|
||||
tempY += speed;
|
||||
}
|
||||
}
|
||||
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_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;
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure player stays within environment bounds
|
||||
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;
|
||||
}
|
||||
|
||||
this->updatePlayerPos(tempX, tempY);
|
||||
};
|
||||
1
resource.rc
Normal file
1
resource.rc
Normal file
@@ -0,0 +1 @@
|
||||
IDI_ICON1 ICON "../img/logo.ico"
|
||||
BIN
sounds/Menu.wav
Normal file
BIN
sounds/Menu.wav
Normal file
Binary file not shown.
BIN
sounds/Playing.wav
Normal file
BIN
sounds/Playing.wav
Normal file
Binary file not shown.
BIN
sounds/Shark-approching.wav
Normal file
BIN
sounds/Shark-approching.wav
Normal file
Binary file not shown.
BIN
sounds/death.wav
Normal file
BIN
sounds/death.wav
Normal file
Binary file not shown.
BIN
sounds/shark.wav
Normal file
BIN
sounds/shark.wav
Normal file
Binary file not shown.
Reference in New Issue
Block a user