Merge branch 'main' of github.com:Kum1ta/PTME_Transcendence

This commit is contained in:
Mathis Degryck
2024-10-07 16:35:19 +02:00
23 changed files with 399 additions and 370 deletions

View File

@ -0,0 +1,195 @@
# **************************************************************************** #
# #
# ::: :::::::: #
# Ball.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: tomoron <tomoron@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2024/10/06 03:24:10 by tomoron #+# #+# #
# Updated: 2024/10/06 17:22:46 by tomoron ### ########.fr #
# #
# **************************************************************************** #
from .GameSettings import GameSettings
import random
import math
class Ball:
def __init__(self):
self.default()
self.obstacles = []
def setStartVel(self, inv):
self.speed = GameSettings.startSpeed
self.vel[0] = self.speed * (random.randint(-50, 50) / 100)
self.vel[1] = self.speed - abs(self.vel[0])
if(inv == 2):
self.vel[1] = -self.vel[1]
def default(self):
self.pos = [0, 0]
self.up = False
self.vel = [0, 0]
self.speed = GameSettings.startSpeed
def setObstacles(self, obstacles):
self.obstacles = obstacles
def solve_quadratic(self, a, b, c):
disc = (b ** 2) - (4 * a * c)
if(disc < 0):
return None
res = (((-b) + math.sqrt(disc)) / ( 2 * a )) + (((-b) - math.sqrt(disc)) / ( 2 * a ))
return(res / 2)
def check_jumper_colision(self, jumper):
jpos = (jumper["pos"]["x"], jumper["pos"]["z"])
pos1 = self.pos
pos2 = self.pos[0] + self.vel[0], self.pos[1] + self.vel[1]
slope = 0
if(pos1[0] - pos2[0] == 0):
slope=100
else:
slope = (pos1[1] - pos2[1])/(pos1[0] - pos2[0])
offset = pos1[1] - (slope * pos1[0])
#salagadou la menchikabou la bibidi bobidi bou
a = 1 + (slope ** 2)
b = ((-jpos[0]) * 2) + (2 * (slope * (-jpos[1] + offset)))
c = (((-jpos[0]) ** 2) + (((-jpos[1]) + offset) ** 2)) - (GameSettings.jumperRadius ** 2)
return(self.solve_quadratic(a, b ,c))
def check_wall_colision(self, wall):
wpos = wall["pos"]["x"]
pos1 = self.pos
pos2 = self.pos[0] +self.vel[0], self.pos[1] + self.vel[1]
slope = 0
if(abs(pos1[1]) <= (GameSettings.wallWidth / 2) + GameSettings.ballRadius):
print("inside")
return(None)
if(pos1[0] - pos2[0] == 0):
slope=100
else:
slope = (pos1[1] - pos2[1])/(pos1[0] - pos2[0])
offset = pos1[1] - (slope * pos1[0])
if(slope == 0):
return(None)
wallSide = (GameSettings.wallWidth / 2) + GameSettings.ballRadius
if(pos1[1] < 0):
wallSide *= -1
hitPos = (wallSide - offset) / slope
print(f'{hitPos=}')
relPos = wpos - hitPos
print("relative position : ", relPos)
print("max colision : ", (GameSettings.wallLength / 2) + GameSettings.ballRadius)
if(abs(relPos) < (GameSettings.wallLength / 2) + GameSettings.ballRadius):
return(hitPos)
print("not in wall 1")
return(None)
def check_collision_obstacles(self):
min_time = -1
for x in self.obstacles:
if x["isUp"] != self.up:
continue
pos = None
if x["type"] == 1:
pos = self.check_jumper_colision(x)
elif x["type"] == 2:
pos = self.check_wall_colision(x)
if(pos == None):
continue
dist = pos - self.pos[0]
time = 0
if(self.vel[0] != 0):
time = dist / self.vel[0]
else:
time = -1
if(time > 0):
if(min_time == -1):
min_time = time
else:
min_time = (min(min_time, time))
return(min_time)
def getTimeUntilColision(self, limitNeg, limitPos, position, velocity):
if(not velocity):
return(-1)
limit = GameSettings.limits[limitNeg] if velocity < 0 else GameSettings.limits[limitPos]
wallDistance = max(limit, position) - min(limit, position)
colision_time = wallDistance / abs(velocity)
return(colision_time)
def getSleepTime(self):
time_x = self.getTimeUntilColision("left","right", self.pos[0], self.vel[0])
time_z = self.getTimeUntilColision("back","front", self.pos[1], self.vel[1])
time_objects = self.check_collision_obstacles()
if(time_objects != -1):
time_x = min(time_x, time_objects)
if(time_x == -1):
return(time_z)
if(time_z == -1):
return(time_x)
return(min(time_x, time_z))
def getPlayerDistance(self, player, ballPos):
playerPos = player["pos"]
return(playerPos - ballPos[0])
def twoPointsDistance(self, pos1, pos2):
return(math.sqrt(((pos2[0] - pos1[0]) ** 2) + ((pos2[1] - pos1[1]) ** 2)))
def checkJumpersDistance(self, ballPos, p1, p2):
for i in range(0, len(self.obstacles)):
if(self.obstacles[i]["type"] != 1):
continue;
if(self.obstacles[i]["isUp"] != self.up):
continue
if(self.twoPointsDistance((self.obstacles[i]["pos"]["x"], self.obstacles[i]["pos"]["z"]), ballPos) < GameSettings.jumperRadius):
p1.socket.sync_send({"type":"game", "content":{"action":8,"name":self.obstacles[i]["name"]}})
p2.socket.sync_send({"type":"game", "content":{"action":8,"name":self.obstacles[i]["name"]}})
self.up = not self.up
def checkWallsColision(self, ballPos):
for i in range(0, len(self.obstacles)):
if(self.obstacles[i]["type"] != 2):
continue;
if(self.obstacles[i]["isUp"] != self.up):
continue;
if(abs(ballPos[1]) <= (GameSettings.wallWidth / 2) + GameSettings.ballRadius):
if(abs(self.obstacles[i]["pos"]["x"] - ballPos[0]) < (GameSettings.wallLength / 2) + GameSettings.ballRadius):
return(True)
return(False)
def increaseSpeed(self):
self.vel[0] += (GameSettings.bounceSpeedIncrease * (self.vel[0] / self.speed))
self.vel[1] += (GameSettings.bounceSpeedIncrease * (self.vel[1] / self.speed))
self.speed += GameSettings.bounceSpeedIncrease
async def update(self, delta, p1, p2):
print("AAAAAAAAAAAAAAAAAAAAAAA update")
self.pos[0] += (delta * self.vel[0])
self.pos[1] += (delta * self.vel[1])
if(self.pos[1] <= GameSettings.limits["back"] or self.pos[1] >= GameSettings.limits["front"]):
player = p2.pos if self.pos[1] < 0 else p1.pos
playerDistance = self.getPlayerDistance(player, self.pos)
if(playerDistance >= -(GameSettings.playerLength / 2) and playerDistance <= GameSettings.playerLength / 2 and player["up"] == self.up):
self.vel[0] = -((self.speed * 0.80) * (playerDistance / (GameSettings.playerLength / 2)))
self.vel[1] = self.speed - abs(self.vel[0])
if(self.pos[1] > 0):
self.vel[1] = -self.vel[1]
p1.socket.sync_send({"type":"game","content":{"action":4, "is_opponent": self.pos[1] < 0}})
p2.socket.sync_send({"type":"game","content":{"action":4, "is_opponent": self.pos[1] > 0}})
else:
return(1 if self.pos[1] < 0 else 2)
elif(self.pos[0] <= GameSettings.limits["left"] or self.pos[0] >= GameSettings.limits["right"]):
self.vel[0] = -self.vel[0]
elif(self.checkWallsColision(self.pos)):
self.vel[1] = -self.vel[1]
self.checkJumpersDistance(self.pos, p1, p2)
self.increaseSpeed()
return(0)
#AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa

View File

@ -6,13 +6,15 @@
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ # # By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/09/13 16:20:58 by tomoron #+# #+# # # Created: 2024/09/13 16:20:58 by tomoron #+# #+# #
# Updated: 2024/10/05 03:50:25 by tomoron ### ########.fr # # Updated: 2024/10/06 17:40:23 by tomoron ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
from asgiref.sync import sync_to_async from asgiref.sync import sync_to_async
from .Player import Player from .Player import Player
from .models import GameResults, User from .models import GameResults, User
from .GameSettings import GameSettings
from .Ball import Ball
import time import time
import json import json
import asyncio import asyncio
@ -22,60 +24,19 @@ import math
class Game: class Game:
waitingForPlayerLock = False waitingForPlayerLock = False
waitingForPlayer = None waitingForPlayer = None
ballRadius = 0.15
playerLength = 1 + (ballRadius * 4)
limits = {
"left" : -3.5 + ballRadius,
"right" : 3.5 - ballRadius,
"back" : -6.25 + ballRadius,
"front" : 6.25 - ballRadius
}
mapLength = 13
startSpeed = 6
jumperRadius = 0.2
wallsPos = [
{ "type":2, "pos": {"x": 1, "y": 0, "z": 1}, "isUp": False},
{ "type":2, "pos": {"x": 1, "y": 0, "z": 1}, "isUp": True},
{ "type":2, "pos": {"x": -1, "y": 0, "z": 1}, "isUp": False},
{ "type":2, "pos": {"x": -1, "y": 0, "z": 1}, "isUp": True}
]
jumpersPos = [
{ "type":1, "name":"J0", "pos":{"x": -1.5, "y": 0.2, "z":mapLength/4}, "isUp": False },
{ "type":1, "name":"J1", "pos":{"x": -1.5, "y": 3.2, "z": mapLength / 4}, "isUp": True },
{ "type":1, "name":"J2", "pos":{"x": 1.5, "y": 0.2, "z": mapLength / 4}, "isUp": False },
{ "type":1, "name":"J3", "pos":{"x": 1.5, "y": 3.2, "z": mapLength / 4}, "isUp": True },
{ "type":1, "name":"J4", "pos":{"x": -1.5, "y": 0.2, "z": -mapLength / 4}, "isUp": False },
{ "type":1, "name":"J5", "pos":{"x": -1.5, "y": 3.2, "z": -mapLength / 4}, "isUp": True },
{ "type":1, "name":"J6", "pos":{"x": 1.5, "y": 0.2, "z": -mapLength / 4}, "isUp": False },
{ "type":1, "name":"J7", "pos":{"x": 1.5, "y": 3.2, "z": -mapLength / 4}, "isUp": True }
]
skins = [
{id: 0, 'color': 0xff53aa, 'texture': None},
{id: 1, 'color': 0xaa24ea, 'texture': None},
{id: 2, 'color': 0x2c9c49, 'texture': None},
{id: 3, 'color': 0x101099, 'texture': None},
{id: 4, 'color': None, 'texture': '/static/img/skin/1.jpg'},
{id: 5, 'color': None, 'texture': '/static/img/skin/2.jpg'},
{id: 6, 'color': None, 'texture': '/static/img/skin/3.jpg'},
{id: 7, 'color': None, 'texture': '/static/img/skin/4.jpg'},
]
wallLength = 1
wallWidth = 0.05
bounceSpeedIncrease = 0.2
maxScore = 5
def __init__(self, socket, withBot, skinId = 0, opponent = None): def __init__(self, socket, withBot, skinId = 0, opponent = None):
self.p1 = Player() self.p1 = None
self.p2 = Player() self.p2 = None
self.started = False self.started = False
self.end = False self.end = False
self.left = None self.left = None
self.winner = None self.winner = None
self.gameStart = 0 self.gameStart = 0
self.gameTime = 0
self.ballPos = {"pos":(0, 0), "up": False} self.ball = Ball()
self.ballVel = (0, 0) self.speed = GameSettings.startSpeed
self.speed = Game.startSpeed
self.score = [0, 0] self.score = [0, 0]
self.obstacles = [] self.obstacles = []
self.lastWin = 2 self.lastWin = 2
@ -94,7 +55,7 @@ class Game:
socket.onlinePlayers[opponent].sync_send({"type":"invitation","content":{"invitor":socket.id, "username":socket.username}}) socket.onlinePlayers[opponent].sync_send({"type":"invitation","content":{"invitor":socket.id, "username":socket.username}})
else: else:
while(Game.waitingForPlayerLock): while(Game.waitingForPlayerLock):
time.sleep(0.05) continue
Game.waitingForPlayerLock = True Game.waitingForPlayerLock = True
if(Game.waitingForPlayer == None): if(Game.waitingForPlayer == None):
Game.waitingForPlayer = self Game.waitingForPlayer = self
@ -105,29 +66,33 @@ class Game:
Game.waitingForPlayer = None Game.waitingForPlayer = None
Game.waitingForPlayerLock = False Game.waitingForPlayerLock = False
def __del__(self):
print("game destroy")
def obstaclesInvLength(self): def obstaclesInvLength(self):
for x in self.obstacles: for x in self.obstacles:
x["pos"]["z"] = -x["pos"]["z"] x["pos"]["z"] = -x["pos"]["z"]
x["pos"]["x"] = -x["pos"]["x"] x["pos"]["x"] = -x["pos"]["x"]
def genObstacles(self): def genObstacles(self):
for x in Game.wallsPos: for x in GameSettings.wallsPos:
if random.randint(1, 100) < 70: if random.randint(1, 100) < 70:
self.obstacles.append(x) self.obstacles.append(x)
i = 0 i = 0
down = False down = False
while(i < len(Game.jumpersPos) - 2): while(i < len(GameSettings.jumpersPos) - 2):
if(random.randint(1, 100) < 50): if(random.randint(1, 100) < 50):
self.obstacles.append(Game.jumpersPos[i]) self.obstacles.append(GameSettings.jumpersPos[i])
down = True down = True
else: else:
self.obstacles.append(Game.jumpersPos[i + 1]) self.obstacles.append(GameSettings.jumpersPos[i + 1])
i+=2 i+=2
if not down: if not down:
self.obstacles.append(Game.jumpersPos[i]) self.obstacles.append(GameSettings.jumpersPos[i])
else: else:
self.obstacles.append(Game.jumpersPos[i + 1]) self.obstacles.append(GameSettings.jumpersPos[i + 1])
self.ball.setObstacles(self.obstacles)
self.p1.socket.sync_send({"type":"game", "content":{"action":7, "content":self.obstacles}}) self.p1.socket.sync_send({"type":"game", "content":{"action":7, "content":self.obstacles}})
self.obstaclesInvLength() self.obstaclesInvLength()
self.p2.socket.sync_send({"type":"game", "content":{"action":7, "content":self.obstacles}}) self.p2.socket.sync_send({"type":"game", "content":{"action":7, "content":self.obstacles}})
@ -135,19 +100,18 @@ class Game:
def join(self, socket, skin = 0): def join(self, socket, skin = 0):
try: try:
if(self.p1.socket == None): if(self.p1 == None):
print("game created, set as player 1") print("game created, set as player 1")
self.p1.socket = socket self.p1 = Player(socket, self)
self.p1.skin = skin self.p1.skin = skin
else: else:
if(self.opponentLock != None and self.opponentLock != socket.id): if(self.opponentLock != None and self.opponentLock != socket.id):
socket.sendError("You are not invited to this game", 9103) socket.sendError("You are not invited to this game", 9103)
return; return;
print("joined game, set as player 2") print("joined game, set as player 2")
self.p2.socket = socket self.p2 = Player(socket, self)
self.p2.skin = skin self.p2.skin = skin
socket.game = self if(self.p2 != None and self.p1 != None):
if(self.p2.socket != None and self.p1.socket != None):
print("both players here, send opponent to both players") print("both players here, send opponent to both players")
self.p1.socket.sync_send({"type":"game", "content":{"action":1,"id":self.p2.socket.id,"username":self.p2.socket.username, "skin":self.p2.skin}}) self.p1.socket.sync_send({"type":"game", "content":{"action":1,"id":self.p2.socket.id,"username":self.p2.socket.username, "skin":self.p2.skin}})
self.p2.socket.sync_send({"type":"game", "content":{"action":1,"id":self.p1.socket.id,"username":self.p1.socket.username, "skin":self.p1.skin}}) self.p2.socket.sync_send({"type":"game", "content":{"action":1,"id":self.p1.socket.id,"username":self.p1.socket.username, "skin":self.p1.skin}})
@ -211,131 +175,25 @@ class Game:
def sendNewBallInfo(self, reset = False): def sendNewBallInfo(self, reset = False):
print("send new ball info") print("send new ball info")
if(reset): if(reset):
gameTime = 0 self.gameTime = 0
self.gameStart = time.time() * 1000
else:
gameTime = (time.time() * 1000) - self.gameStart
if(self.p1.socket): if(self.p1.socket):
self.p1.socket.sync_send({"type":"game", "content":{"action":5, self.p1.socket.sync_send({"type":"game", "content":{"action":5,
"pos" : [self.ballPos["pos"][0],self.ballPos["pos"][1]], "pos" : [self.ball.pos[0],self.ball.pos[1]],
"velocity":[self.ballVel[0], self.ballVel[1]], "velocity":[self.ball.vel[0], self.ball.vel[1]],
"game_time":gameTime "game_time":self.gameTime * 1000
}}) }})
if(self.p2.socket): if(self.p2.socket):
self.p2.socket.sync_send({"type":"game","content":{"action":5, self.p2.socket.sync_send({"type":"game","content":{"action":5,
"pos" : [-self.ballPos["pos"][0],-self.ballPos["pos"][1]], "pos" : [-self.ball.pos[0],-self.ball.pos[1]],
"velocity":[-self.ballVel[0], -self.ballVel[1]], "velocity":[-self.ball.vel[0], -self.ball.vel[1]],
"game_time":gameTime "game_time":self.gameTime * 1000
}}) }})
def solve_quadratic(self, a, b, c):
disc = (b ** 2) - (4 * a * c)
if(disc < 0):
return None
res = (((-b) + math.sqrt(disc)) / ( 2 * a )) + (((-b) - math.sqrt(disc)) / ( 2 * a ))
return(res / 2)
def check_jumper_colision(self, jumper):
jpos = (jumper["pos"]["x"], jumper["pos"]["z"])
pos1 = self.ballPos["pos"]
pos2 = self.ballPos["pos"][0] + self.ballVel[0], self.ballPos["pos"][1] + self.ballVel[1]
slope = 0
if(pos1[0] - pos2[0] == 0):
slope=100000
else:
slope = (pos1[1] - pos2[1])/(pos1[0] - pos2[0])
offset = pos1[1] - (slope * pos1[0])
#salagadou la menchikabou la bibidi bobidi bou
a = 1 + (slope ** 2)
b = ((-jpos[0]) * 2) + (2 * (slope * (-jpos[1] + offset)))
c = (((-jpos[0]) ** 2) + (((-jpos[1]) + offset) ** 2)) - (Game.jumperRadius ** 2)
return(self.solve_quadratic(a, b ,c))
def check_wall_colision(self, wall):
wpos = wall["pos"]["x"]
pos1 = self.ballPos["pos"]
pos2 = self.ballPos["pos"][0] +self.ballVel[0], self.ballPos["pos"][1] + self.ballVel[1]
slope = 0
if(abs(pos1[1]) <= (Game.wallWidth / 2) + Game.ballRadius):
print("inside")
return(None)
if(pos1[0] - pos2[0] == 0):
slope=100000
else:
slope = (pos1[1] - pos2[1])/(pos1[0] - pos2[0])
offset = pos1[1] - (slope * pos1[0])
if(slope == 0):
return(None)
wallSide = (Game.wallWidth / 2) + Game.ballRadius
if(pos1[1] < 0):
wallSide *= -1
hitPos = (wallSide - offset) / slope
print(f'{hitPos=}')
relPos = wpos - hitPos
print("relative position : ", relPos)
print("max colision : ", (Game.wallLength / 2) + Game.ballRadius)
if(abs(relPos) < (Game.wallLength / 2) + Game.ballRadius):
return(hitPos)
print("not in wall 1")
return(None)
def check_collision_obstacles(self):
min_time = -1
for x in self.obstacles:
if x["isUp"] != self.ballPos["up"]:
continue
pos = None
if x["type"] == 1:
pos = self.check_jumper_colision(x)
elif x["type"] == 2:
pos = self.check_wall_colision(x)
if(pos == None):
continue
dist = pos - self.ballPos["pos"][0]
time = 0
if(self.ballVel[0] != 0):
time = dist / self.ballVel[0]
else:
time = -1
if(time > 0):
if(min_time == -1):
min_time = time
else:
min_time = (min(min_time, time))
return(min_time)
def getTimeUntilColision(self, limitNeg, limitPos, position, velocity):
if(not velocity):
return(-1)
limit = Game.limits[limitNeg] if velocity < 0 else Game.limits[limitPos]
wallDistance = max(limit, position) - min(limit, position)
colision_time = wallDistance / abs(velocity)
return(colision_time)
def getSleepTime(self):
time_x = self.getTimeUntilColision("left","right", self.ballPos["pos"][0], self.ballVel[0])
time_z = self.getTimeUntilColision("back","front", self.ballPos["pos"][1], self.ballVel[1])
time_objects = self.check_collision_obstacles()
if(time_objects != -1):
time_x = min(time_x, time_objects)
if(time_x == -1):
return(time_z)
if(time_z == -1):
return(time_x)
return(min(time_x, time_z))
def getPlayerDistance(self, player, ballPos):
playerPos = player["pos"]
return(playerPos - ballPos[0])
def checkGameEndGoal(self): def checkGameEndGoal(self):
if(self.score[0] < Game.maxScore and self.score[1] < Game.maxScore): if(self.score[0] < GameSettings.maxScore and self.score[1] < GameSettings.maxScore):
return(False) return(False)
print("someone won the game") print("someone won the game")
winner = 1 if self.score[0] == Game.maxScore else 2 winner = 1 if self.score[0] == GameSettings.maxScore else 2
print("player", winner,"won the game") print("player", winner,"won the game")
self.endGame(winner) self.endGame(winner)
return(True) return(True)
@ -355,85 +213,15 @@ class Game:
self.prepareGame() self.prepareGame()
return; return;
def twoPointsDistance(self, pos1, pos2):
return(math.sqrt(((pos2[0] - pos1[0]) ** 2) + ((pos2[1] - pos1[1]) ** 2)))
def checkJumpersDistance(self, ballPos):
for i in range(0, len(self.obstacles)):
if(self.obstacles[i]["type"] != 1):
continue;
if(self.obstacles[i]["isUp"] != self.ballPos["up"]):
continue
if(self.twoPointsDistance((self.obstacles[i]["pos"]["x"], self.obstacles[i]["pos"]["z"]), ballPos) < Game.jumperRadius):
self.p1.socket.sync_send({"type":"game", "content":{"action":8,"name":self.obstacles[i]["name"]}})
self.p2.socket.sync_send({"type":"game", "content":{"action":8,"name":self.obstacles[i]["name"]}})
self.ballPos["up"] = not self.ballPos["up"]
def checkWallsColision(self, ballPos):
for i in range(0, len(self.obstacles)):
if(self.obstacles[i]["type"] != 2):
continue;
if(self.obstacles[i]["isUp"] != self.ballPos["up"]):
continue;
if(abs(ballPos[1]) < (Game.wallWidth / 2) + Game.ballRadius):
if(abs(self.obstacles[i]["pos"]["x"] - ballPos[0]) < (Game.wallLength / 2) + Game.ballRadius):
print("not in wall 2")
return(True)
return(False)
def increaseSpeed(self):
x = self.ballVel[0] + (Game.bounceSpeedIncrease * (self.ballVel[0] / self.speed))
y = self.ballVel[1] + (Game.bounceSpeedIncrease * (self.ballVel[1] / self.speed))
self.ballVel = (x, y)
self.speed += Game.bounceSpeedIncrease
async def updateBall(self):
print("AAAAAAAAAAAAAAAAAAAAAAA update")
now = time.time()
delta = now - self.lastUpdate
print("delta :", delta)
currentBallPos = self.ballPos["pos"]
velX = self.ballVel[0]
velZ = self.ballVel[1]
newBallPos = (round(currentBallPos[0] + (delta * velX), 5),
round(currentBallPos[1] + (delta * velZ), 5))
if(newBallPos[1] <= Game.limits["back"] or newBallPos[1] >= Game.limits["front"]):
player = self.p2.pos if newBallPos[1] < 0 else self.p1.pos
playerDistance = self.getPlayerDistance(player, newBallPos)
if(playerDistance >= -(Game.playerLength / 2) and playerDistance <= Game.playerLength / 2 and player["up"] == self.ballPos["up"]):
velX = -((self.speed * 0.80) * (playerDistance / (Game.playerLength / 2)))
velZ = self.speed - abs(velX)
if(newBallPos[1] > 0):
velZ = -velZ
self.p1.socket.sync_send({"type":"game","content":{"action":4, "is_opponent": newBallPos[1] < 0}})
self.p2.socket.sync_send({"type":"game","content":{"action":4, "is_opponent": newBallPos[1] > 0}})
else:
await self.scoreGoal(1 if newBallPos[1] < 0 else 2)
return;
elif(newBallPos[0] <= Game.limits["left"] or newBallPos[0] >= Game.limits["right"]):
velX = -velX
elif(self.checkWallsColision(newBallPos)):
velZ = -velZ
self.checkJumpersDistance(newBallPos)
self.ballVel = (velX, velZ)
self.increaseSpeed()
self.lastUpdate = now
self.ballPos["pos"] = newBallPos
self.sendNewBallInfo()
def prepareGame(self, stop = False): def prepareGame(self, stop = False):
self.speed = Game.startSpeed self.speed = GameSettings.startSpeed
self.ballPos = {"pos":(0, 0), "up": False} self.ball.default()
if(stop): if(stop):
self.ballVel = (0, 0) self.ball.vel = [0, 0]
else: else:
velX = self.speed * (random.randint(-50, 50) / 100) self.ball.setStartVel(self.lastWin == 2)
velZ = self.speed - abs(velX)
if(self.lastWin == 2):
velZ = -velZ
self.ballVel = (velX, velZ)
self.sendNewBallInfo(True) self.sendNewBallInfo(True)
self.lastUpdate = time.time() self.gameStart = time.time()
async def gameLoop(self): async def gameLoop(self):
self.started = True self.started = True
@ -442,16 +230,23 @@ class Game:
await asyncio.sleep(3) await asyncio.sleep(3)
self.prepareGame() self.prepareGame()
while(not self.end): while(not self.end):
await self.updateBall() sleep_time = self.ball.getSleepTime()
if(self.end):
break;
sleep_time = self.getSleepTime()
print("sleep time : " , sleep_time) print("sleep time : " , sleep_time)
await asyncio.sleep(sleep_time) if((time.time() - self.gameStart) - self.gameTime < sleep_time):
await asyncio.sleep(sleep_time - ((time.time() - self.gameStart) - self.gameTime))
self.gameTime += sleep_time
goal = await self.ball.update(sleep_time, self.p1, self.p2)
if(goal):
await self.scoreGoal(goal)
else:
self.sendNewBallInfo()
print("game end") print("game end")
if(self.p1.socket.game == self):
self.p1.socket.game = None
if(self.p2.socket.game == self):
self.p2.socket.game = None
await self.saveResults() await self.saveResults()
self.p1.socket.game = None del self
self.p2.socket.game = None
@sync_to_async @sync_to_async
def saveResults(self): def saveResults(self):

View File

@ -0,0 +1,54 @@
# **************************************************************************** #
# #
# ::: :::::::: #
# GameSettings.py :+: :+: :+: #
# +:+ +:+ +:+ #
# By: tomoron <tomoron@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2024/10/06 16:33:56 by tomoron #+# #+# #
# Updated: 2024/10/06 16:34:24 by tomoron ### ########.fr #
# #
# **************************************************************************** #
class GameSettings:
ballRadius = 0.15
playerLength = 1 + (ballRadius * 4)
limits = {
"left" : -3.5 + ballRadius,
"right" : 3.5 - ballRadius,
"back" : -6.25 + ballRadius,
"front" : 6.25 - ballRadius
}
mapLength = 13
startSpeed = 6
jumperRadius = 0.2
wallsPos = [
{ "type":2, "pos": {"x": 1, "y": 0, "z": 1}, "isUp": False},
{ "type":2, "pos": {"x": 1, "y": 0, "z": 1}, "isUp": True},
{ "type":2, "pos": {"x": -1, "y": 0, "z": 1}, "isUp": False},
{ "type":2, "pos": {"x": -1, "y": 0, "z": 1}, "isUp": True}
]
jumpersPos = [
{ "type":1, "name":"J0", "pos":{"x": -1.5, "y": 0.2, "z":mapLength/4}, "isUp": False },
{ "type":1, "name":"J1", "pos":{"x": -1.5, "y": 3.2, "z": mapLength / 4}, "isUp": True },
{ "type":1, "name":"J2", "pos":{"x": 1.5, "y": 0.2, "z": mapLength / 4}, "isUp": False },
{ "type":1, "name":"J3", "pos":{"x": 1.5, "y": 3.2, "z": mapLength / 4}, "isUp": True },
{ "type":1, "name":"J4", "pos":{"x": -1.5, "y": 0.2, "z": -mapLength / 4}, "isUp": False },
{ "type":1, "name":"J5", "pos":{"x": -1.5, "y": 3.2, "z": -mapLength / 4}, "isUp": True },
{ "type":1, "name":"J6", "pos":{"x": 1.5, "y": 0.2, "z": -mapLength / 4}, "isUp": False },
{ "type":1, "name":"J7", "pos":{"x": 1.5, "y": 3.2, "z": -mapLength / 4}, "isUp": True }
]
skins = [
{id: 0, 'color': 0xff53aa, 'texture': None},
{id: 1, 'color': 0xaa24ea, 'texture': None},
{id: 2, 'color': 0x2c9c49, 'texture': None},
{id: 3, 'color': 0x101099, 'texture': None},
{id: 4, 'color': None, 'texture': '/static/img/skin/1.jpg'},
{id: 5, 'color': None, 'texture': '/static/img/skin/2.jpg'},
{id: 6, 'color': None, 'texture': '/static/img/skin/3.jpg'},
{id: 7, 'color': None, 'texture': '/static/img/skin/4.jpg'},
]
wallLength = 1
wallWidth = 0.05
bounceSpeedIncrease = 0.2
maxScore = 5

View File

@ -6,13 +6,17 @@
# By: tomoron <tomoron@student.42.fr> +#+ +:+ +#+ # # By: tomoron <tomoron@student.42.fr> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/10/05 03:22:32 by tomoron #+# #+# # # Created: 2024/10/05 03:22:32 by tomoron #+# #+# #
# Updated: 2024/10/05 03:46:24 by tomoron ### ########.fr # # Updated: 2024/10/06 16:16:26 by tomoron ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
class Player(): class Player():
def __init__(self): def __init__(self, socket, game):
self.socket = None self.socket = socket
socket.game = game
self.ready = False self.ready = False
self.pos = {"pos":0, "up": False} self.pos = {"pos":0, "up": False}
self.skin = 0 self.skin = 0
def __del__(self):
print("player destroy")

View File

@ -6,11 +6,12 @@
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ # # By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/09/11 17:07:08 by tomoron #+# #+# # # Created: 2024/09/11 17:07:08 by tomoron #+# #+# #
# Updated: 2024/09/27 17:39:59 by tomoron ### ########.fr # # Updated: 2024/10/06 16:39:52 by tomoron ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
from ...Game import Game from ...Game import Game
from ...GameSettings import GameSettings
async def start(socket, content): async def start(socket, content):
if(socket.game != None): if(socket.game != None):
@ -21,7 +22,7 @@ async def start(socket, content):
socket.sendError("Your opponent isn't online",9032) socket.sendError("Your opponent isn't online",9032)
return; return;
skinId = content.get("skinId", 0) skinId = content.get("skinId", 0)
if(skinId < 0 or skinId >= len(Game.skins)): if(skinId < 0 or skinId >= len(GameSettings.skins)):
socket.sendError("Skin id out of range", 9033) socket.sendError("Skin id out of range", 9033)
return; return;
Game(socket, content.get("with_bot", False),skinId ,opponent) Game(socket, content.get("with_bot", False),skinId ,opponent)

View File

@ -25,7 +25,7 @@ urlpatterns = [
path("multiOnlineGamePage", views.multiOnlineGamePage, name='multiOnlineGamePage'), path("multiOnlineGamePage", views.multiOnlineGamePage, name='multiOnlineGamePage'),
path("waitingGamePage", views.waitingGamePage, name='waitingGamePage'), path("waitingGamePage", views.waitingGamePage, name='waitingGamePage'),
path("profilPage", views.profilPage, name='profilPage'), path("profilPage", views.profilPage, name='profilPage'),
# path("game", views.game, name='game'), path("game", views.game, name='game'),
path("wait_game", views.game, name='wait_game'), path("wait_game", views.game, name='wait_game'),
#path("tournament", views.tournament, name='tournament'), #path("tournament", views.tournament, name='tournament'),
path("login42", views.login42, name='login42'), path("login42", views.login42, name='login42'),

View File

@ -6,7 +6,7 @@
# By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ # # By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ # # +#+#+#+#+#+ +#+ #
# Created: 2024/09/09 14:31:30 by tomoron #+# #+# # # Created: 2024/09/09 14:31:30 by tomoron #+# #+# #
# Updated: 2024/10/04 21:06:20 by tomoron ### ########.fr # # Updated: 2024/10/06 16:28:47 by tomoron ### ########.fr #
# # # #
# **************************************************************************** # # **************************************************************************** #
@ -169,6 +169,7 @@ class WebsocketHandler(AsyncWebsocketConsumer):
@multimethod @multimethod
def sync_send(self, data: Union[dict,str]): def sync_send(self, data: Union[dict,str]):
if(not self.online): if(not self.online):
print("cancel send, socket not online")
return return
txt_data = None txt_data = None
if(type(data) is dict): if(type(data) is dict):
@ -198,6 +199,8 @@ class WebsocketHandler(AsyncWebsocketConsumer):
def printDebug(self, request, typeRequest, error=None): def printDebug(self, request, typeRequest, error=None):
try: try:
if (self.debugMode and typeRequest == 0): if (self.debugMode and typeRequest == 0):
if(request["type"] == "game" and request.get("content", {}).get("action", 0) == 4):
return
print("\033[0;34m|----- New received request -----|\033[0;0m") print("\033[0;34m|----- New received request -----|\033[0;0m")
#print("User :", self.username) #print("User :", self.username)
#print("Token :", self.token) #print("Token :", self.token)

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/25 00:00:21 by edbernar #+# #+# */ /* Created: 2024/08/25 00:00:21 by edbernar #+# #+# */
/* Updated: 2024/10/01 23:03:17 by edbernar ### ########.fr */ /* Updated: 2024/10/06 23:49:15 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -50,6 +50,8 @@ class Page
sendRequest("game", {action: 2}); sendRequest("game", {action: 2});
if (thisClass.actualPage == TournamentPage) if (thisClass.actualPage == TournamentPage)
sendRequest("tournament", {action: 1}); sendRequest("tournament", {action: 1});
if (thisClass.actualPage == WaitingGamePage)
sendRequest("game", {action: 2});
thisClass.changePage(thisClass.availablePages[i].name, true, arg, !thisClass.availablePages[i].suffix); thisClass.changePage(thisClass.availablePages[i].name, true, arg, !thisClass.availablePages[i].suffix);
return ; return ;
} }
@ -89,6 +91,11 @@ class Page
.then(data => { .then(data => {
data.text().then(text => { data.text().then(text => {
document.body.innerHTML = text; document.body.innerHTML = text;
for (let i = 0; i < this.availablePages.length; i++)
{
if (this.actualPage === this.availablePages[i].class)
document.precedentPage = this.availablePages[i].name;
}
this.actualPage = this.availablePages[i].class; this.actualPage = this.availablePages[i].class;
document.title = this.availablePages[i].title; document.title = this.availablePages[i].title;
if (!isBack && !this.wasRefresh) if (!isBack && !this.wasRefresh)

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/29 22:36:43 by edbernar #+# #+# */ /* Created: 2024/09/29 22:36:43 by edbernar #+# #+# */
/* Updated: 2024/10/01 21:58:57 by edbernar ### ########.fr */ /* Updated: 2024/10/06 16:42:07 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -16,6 +16,7 @@ const url_files = {
gameboyModel: '/static/models3D/homePage/gameboy.glb', gameboyModel: '/static/models3D/homePage/gameboy.glb',
tvModel: '/static/models3D/homePage/tv.glb', tvModel: '/static/models3D/homePage/tv.glb',
bannerModel: '/static/models3D/multiOnlineGame/banner.glb', bannerModel: '/static/models3D/multiOnlineGame/banner.glb',
infinitPlane: '/static/models3D/homePage/infinitPlane.glb',
pongVideo: '/static/video/homePage/pong.mp4', pongVideo: '/static/video/homePage/pong.mp4',
notLoginVideo: '/static/video/homePage/notLogin.webm', notLoginVideo: '/static/video/homePage/notLogin.webm',

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/22 23:13:53 by edbernar #+# #+# */ /* Created: 2024/08/22 23:13:53 by edbernar #+# #+# */
/* Updated: 2024/10/03 02:33:35 by edbernar ### ########.fr */ /* Updated: 2024/10/06 16:47:57 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -24,7 +24,6 @@ class Screen
screenMaterial = null; screenMaterial = null;
canvasVideo = null; canvasVideo = null;
interval = null; interval = null;
intervalLight = null;
constructor(scene) constructor(scene)
{ {
@ -37,9 +36,7 @@ class Screen
tv.geometry.center(); tv.geometry.center();
this.tv = tv; this.tv = tv;
tv.position.set(0, 0.99, 2); tv.position.set(0, 0.99, 2);
tv.material = new THREE.MeshPhysicalMaterial({color: 0x454545}); tv.material = new THREE.MeshPhysicalMaterial({color: 0x050505});
tv.material.roughness = 1;
tv.material.metalness = 1.05;
tv.scale.set(0.05, 0.05, 0.05); tv.scale.set(0.05, 0.05, 0.05);
tv.castShadow = true; tv.castShadow = true;
tv.receiveShadow = true; tv.receiveShadow = true;
@ -159,8 +156,6 @@ class Screen
dispose() dispose()
{ {
this.#disposeVideo(); this.#disposeVideo();
if (this.intervalLight)
clearInterval(this.intervalLight);
} }

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/22 17:19:17 by edbernar #+# #+# */ /* Created: 2024/08/22 17:19:17 by edbernar #+# #+# */
/* Updated: 2024/10/03 02:39:58 by edbernar ### ########.fr */ /* Updated: 2024/10/06 23:37:28 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -47,6 +47,7 @@ class Home3D
static dispose() static dispose()
{ {
document.addEventListener('scroll', mouseTracker);
window.removeEventListener('resize', windowUpdater); window.removeEventListener('resize', windowUpdater);
document.removeEventListener('mousemove', mouseTracker); document.removeEventListener('mousemove', mouseTracker);
document.removeEventListener('click', redirection); document.removeEventListener('click', redirection);
@ -101,7 +102,7 @@ function home3D()
const loader = new GLTFLoader(); const loader = new GLTFLoader();
let actualVideo = -1; let actualVideo = -1;
let globalSpeed = 0.75; let globalSpeed = 0.75;
const ambiantLight = new THREE.AmbientLight(0xffffff, 35); const ambiantLight = new THREE.AmbientLight(0xffffff, 1);
const video = { const video = {
pong: files.pongVideo, pong: files.pongVideo,
login: files.notLoginVideo login: files.notLoginVideo
@ -117,7 +118,7 @@ function home3D()
isInFade = false; isInFade = false;
spotLight = new THREE.SpotLight(0xffffff, 1000); spotLight = new THREE.SpotLight(0xffffff, 1000);
spotLight.angle = Math.PI / 6; // angle d'ouverture spotLight.angle = Math.PI / 6;
spotLight.penumbra = 0.5; spotLight.penumbra = 0.5;
spotLight.decay = 2; spotLight.decay = 2;
spotLight.distance = 50; spotLight.distance = 50;
@ -128,10 +129,10 @@ function home3D()
if (Math.random() % 100 > 0.99) if (Math.random() % 100 > 0.99)
video.pong = files.easterEggVideo; video.pong = files.easterEggVideo;
// newBgWall();
putObject(files.lampModel, -2.5, 0, 2.5, 3, 0, Math.PI + Math.PI / 8, 0); putObject(files.lampModel, -2.5, 0, 2.5, 3, 0, Math.PI + Math.PI / 8, 0);
putObject(files.plantModel, 1.5, 0, 3, 0.5, 0, 0, 0); putObject(files.plantModel, 1.5, 0, 3, 0.5, 0, 0, 0);
putObject(files.gameboyModel, -0.5, -0.075, 0.5, 0.1, 0, 0.4, 0); putObject(files.gameboyModel, -0.5, -0.075, 0.5, 0.1, 0, 0.4, 0);
putObject(files.infinitPlane, -1, 0, 0, 10, 0, Math.PI / 2 + 0.5, 0, 0x303030);
renderer.toneMapping = THREE.LinearToneMapping; renderer.toneMapping = THREE.LinearToneMapping;
renderer.shadowMap.enabled = true; renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap; renderer.shadowMap.type = THREE.PCFSoftShadowMap;
@ -141,7 +142,6 @@ function home3D()
scene.background = new THREE.Color(0x020202) scene.background = new THREE.Color(0x020202)
scene.add(ambiantLight); scene.add(ambiantLight);
createPlane();
createCube(); createCube();
document.body.getElementsByClassName('homeSection')[0].appendChild(renderer.domElement); document.body.getElementsByClassName('homeSection')[0].appendChild(renderer.domElement);
@ -149,6 +149,7 @@ function home3D()
mouse.x = 9999; mouse.x = 9999;
mouse.y = 9999; mouse.y = 9999;
document.addEventListener('mousemove', mouseTracker); document.addEventListener('mousemove', mouseTracker);
document.addEventListener('scroll', mouseTracker);
composer = new EffectComposer(renderer); composer = new EffectComposer(renderer);
renderPass = new RenderPass(scene, camera); renderPass = new RenderPass(scene, camera);
@ -172,7 +173,7 @@ function home3D()
if (camera.position.x < 3.3 && interval) if (camera.position.x < 3.3 && interval)
fadeInOut(); fadeInOut();
if (dofPass.materialBokeh.uniforms.aperture.value > 0 && interval) if (dofPass.materialBokeh.uniforms.aperture.value > 0 && interval)
dofPass.materialBokeh.uniforms.aperture.value -= 0.0001; dofPass.materialBokeh.uniforms.aperture.value -= 0.0003;
if (camera.position.x < 3 && interval) if (camera.position.x < 3 && interval)
{ {
clearInterval(interval); clearInterval(interval);
@ -240,7 +241,7 @@ function home3D()
{ {
if (clickDetect) if (clickDetect)
{ {
document.removeEventListener('click', redirection); document.getElementsByTagName('canvas')[0].removeEventListener('click', redirection);
clickDetect = false; clickDetect = false;
} }
if (playButtonMouseOver || intersects[0].object == screen.screen) if (playButtonMouseOver || intersects[0].object == screen.screen)
@ -257,7 +258,7 @@ function home3D()
{ {
if (!clickDetect && userMeInfo.id > 0) if (!clickDetect && userMeInfo.id > 0)
{ {
document.addEventListener('click', redirection); document.getElementsByTagName('canvas')[0].addEventListener('click', redirection);
clickDetect = true; clickDetect = true;
} }
} }
@ -271,10 +272,11 @@ function home3D()
composer.render(); composer.render();
} }
function putObject(objUrl, x, y, z, scale, rX, rY, rZ) { function putObject(objUrl, x, y, z, scale, rX, rY, rZ, color = 0x080808)
{
loader.load(objUrl, (gltf) => { loader.load(objUrl, (gltf) => {
const group = new THREE.Group(); const group = new THREE.Group();
const material = new THREE.MeshPhysicalMaterial({color: 0x080808}); const material = new THREE.MeshPhysicalMaterial({color: color});
gltf.scene.children.forEach(elem => { gltf.scene.children.forEach(elem => {
elem.traverse((child) => { elem.traverse((child) => {
@ -294,21 +296,6 @@ function home3D()
}); });
} }
function newBgWall()
{
const geometry = new THREE.BoxGeometry(100, 100, 0.1);
const material = new THREE.MeshStandardMaterial({color: 0x020202});
const mesh = new THREE.Mesh(geometry, material);
const geometry2 = new THREE.BoxGeometry(10, 10, 0.1);
const material2 = new THREE.MeshStandardMaterial({color: 0x020202});
const mesh2 = new THREE.Mesh(geometry2, material2);
mesh.position.set(0, 0, 5);
scene.add(mesh);
mesh2.position.set(-5, 0, 0);
mesh2.rotateY(Math.PI / 2);
scene.add(mesh2);
}
function createCube() function createCube()
{ {
const geometry = new THREE.BoxGeometry(5, 5, 0.1); const geometry = new THREE.BoxGeometry(5, 5, 0.1);
@ -319,18 +306,6 @@ function home3D()
scene.add(mesh); scene.add(mesh);
} }
function createPlane()
{
const geometry = new THREE.PlaneGeometry(500, 500);
const material = new THREE.MeshPhysicalMaterial({side: THREE.DoubleSide, color: 0x020202});
const mesh = new THREE.Mesh(geometry, material);
mesh.position.set(0, 0, 0);
mesh.rotateX(-(Math.PI / 2));
mesh.receiveShadow = true;
scene.add(mesh);
}
function fadeInOut() { function fadeInOut() {
if (isInFade) if (isInFade)
return; return;

View File

@ -3,10 +3,10 @@
/* ::: :::::::: */ /* ::: :::::::: */
/* main.js :+: :+: :+: */ /* main.js :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: madegryc <madegryc@student.42.fr> +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/22 17:08:46 by madegryc #+# #+# */ /* Created: 2024/08/22 17:08:46 by madegryc #+# #+# */
/* Updated: 2024/10/05 22:12:30 by madegryc ### ########.fr */ /* Updated: 2024/10/06 17:00:12 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -48,6 +48,8 @@ class LobbyPage
waitForLogin().then(() => usernameP.innerHTML = userMeInfo.username); waitForLogin().then(() => usernameP.innerHTML = userMeInfo.username);
else else
usernameP.innerHTML = userMeInfo.username; usernameP.innerHTML = userMeInfo.username;
if (usernameP.length > 8)
usernameP.innerHTML = usernameP.innerHTML.substring(0, 8) + '...';
LiveChat.create(); LiveChat.create();
inputUser.addEventListener('input', searchUser); inputUser.addEventListener('input', searchUser);
loginButton.addEventListener('click', showMenu); loginButton.addEventListener('click', showMenu);

View File

@ -3,10 +3,10 @@
/* ::: :::::::: */ /* ::: :::::::: */
/* main.js :+: :+: :+: */ /* main.js :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: madegryc <madegryc@student.42.fr> +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/07 17:40:15 by edbernar #+# #+# */ /* Created: 2024/08/07 17:40:15 by edbernar #+# #+# */
/* Updated: 2024/10/05 22:32:01 by madegryc ### ########.fr */ /* Updated: 2024/10/06 17:01:31 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -35,7 +35,7 @@ class Login
button42.addEventListener('click', redirection); button42.addEventListener('click', redirection);
if (userMeInfo.id !== -1) if (userMeInfo.id !== -1)
{ {
usernameNode = document.createTextNode(userMeInfo.username); usernameNode = document.createTextNode(userMeInfo.username.lenght > 8 ? userMeInfo.username.substring(0, 8) + '...' : userMeInfo.username);
loginButton.replaceChild(usernameNode, pLoginButton); loginButton.replaceChild(usernameNode, pLoginButton);
loginButton.addEventListener('click', showMenu); loginButton.addEventListener('click', showMenu);
window.addEventListener('resize', movePopMenuLoginButton); window.addEventListener('resize', movePopMenuLoginButton);

View File

@ -3,10 +3,10 @@
/* ::: :::::::: */ /* ::: :::::::: */
/* Ball.js :+: :+: :+: */ /* Ball.js :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: madegryc <madegryc@student.42.fr> +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/20 17:02:47 by edbernar #+# #+# */ /* Created: 2024/08/20 17:02:47 by edbernar #+# #+# */
/* Updated: 2024/09/30 19:17:05 by madegryc ### ########.fr */ /* Updated: 2024/10/06 15:57:46 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -44,17 +44,10 @@ class Ball
{ {
this.object = this.#createBall(); this.object = this.#createBall();
this.centerPos = map.centerPos; this.centerPos = map.centerPos;
this.centerPos.y += this.object.geometry.parameters.radius; this.centerPos.y = this.object.geometry.parameters.radius;
this.limits = map.playerLimits; this.limits = map.playerLimits;
this.resetPosBall(); this.resetPosBall();
scene.add(this.object); scene.add(this.object);
// this.world = new CANNON.World();
// this.ballBody = new CANNON.Body({
// shape: new CANNON.Sphere(0.15),
// mass: 10,
// });
// this.ballBody.position.copy(this.object.position);
// this.world.addBody(this.ballBody);
} }
#createBall() #createBall()
@ -71,7 +64,7 @@ class Ball
resetPosBall() resetPosBall()
{ {
this.setPosition(this.centerPos.x, this.centerPos.y, this.centerPos.z); this.setPosition(this.centerPos.x, this.object.geometry.parameters.radius * 2, this.centerPos.z);
} }
resetScaleBall() resetScaleBall()

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/20 14:52:55 by hubourge #+# #+# */ /* Created: 2024/08/20 14:52:55 by hubourge #+# #+# */
/* Updated: 2024/10/03 14:40:41 by edbernar ### ########.fr */ /* Updated: 2024/10/06 16:12:40 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -678,7 +678,8 @@ class Map
clearInterval(interval2); clearInterval(interval2);
interval2 = null; interval2 = null;
} }
scene.remove(this.banner); if (this.banner)
scene.remove(this.banner);
}; };
animationGoal(cordX, cordY, cordZ, nameObject, funcCreateObject) animationGoal(cordX, cordY, cordZ, nameObject, funcCreateObject)
@ -714,6 +715,8 @@ class Map
#clearAnimationGoal() #clearAnimationGoal()
{ {
if (!this.arrObject)
return ;
for (let i = 0; i < this.arrObject.length; i++) for (let i = 0; i < this.arrObject.length; i++)
{ {
if (this.arrObject[i].type == "goalObject") if (this.arrObject[i].type == "goalObject")

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/18 00:30:31 by edbernar #+# #+# */ /* Created: 2024/08/18 00:30:31 by edbernar #+# #+# */
/* Updated: 2024/10/05 02:41:30 by edbernar ### ########.fr */ /* Updated: 2024/10/06 16:15:27 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -194,32 +194,36 @@ class Player
}, 10); }, 10);
setTimeout(() => { setTimeout(() => {
console.log("Player : " + lastSelectedGoal);
map.animationGoal(this.object.position.x, this.object.position.y, this.object.position.z, this.playerGoalAnimation, lastSelectedGoal ? lastSelectedGoal : availableGoals[0]); map.animationGoal(this.object.position.x, this.object.position.y, this.object.position.z, this.playerGoalAnimation, lastSelectedGoal ? lastSelectedGoal : availableGoals[0]);
}, 1000); }, 1000);
setTimeout(() => { setTimeout(() => {
clearInterval(interval); if (interval)
document.getElementsByTagName('canvas')[canvasIndex].style.animation = null; clearInterval(interval);
document.getElementsByTagName('canvas')[canvasIndex].style.animation = 'fadeInGames 0.99s'; interval = null;
document.getElementsByTagName('canvas')[canvasIndex].style.filter = 'brightness(0)'; if (document.getElementsByTagName('canvas') && document.getElementsByTagName('canvas')[canvasIndex])
{
setTimeout(() => {
this.camera = tmp;
this.object.material.color.copy(startColor);
isOnPointAnim = false;
if (!this.cameraFixed)
{
this.setCameraPosition(
this.object.position.x,
this.object.position.y - (this.object.position.y >= this.limits.up ? 0.7 : -0.7),
this.object.position.z + 1.5
);
}
document.getElementsByTagName('canvas')[canvasIndex].style.animation = null; document.getElementsByTagName('canvas')[canvasIndex].style.animation = null;
document.getElementsByTagName('canvas')[canvasIndex].style.animation = 'fadeOutGames 0.99s'; document.getElementsByTagName('canvas')[canvasIndex].style.animation = 'fadeInGames 0.99s';
document.getElementsByTagName('canvas')[canvasIndex].style.filter = 'brightness(1)'; document.getElementsByTagName('canvas')[canvasIndex].style.filter = 'brightness(0)';
}, 400);
setTimeout(() => {
this.camera = tmp;
this.object.material.color.copy(startColor);
isOnPointAnim = false;
if (!this.cameraFixed)
{
this.setCameraPosition(
this.object.position.x,
this.object.position.y - (this.object.position.y >= this.limits.up ? 0.7 : -0.7),
this.object.position.z + 1.5
);
}
document.getElementsByTagName('canvas')[canvasIndex].style.animation = null;
document.getElementsByTagName('canvas')[canvasIndex].style.animation = 'fadeOutGames 0.99s';
document.getElementsByTagName('canvas')[canvasIndex].style.filter = 'brightness(1)';
}, 400);
}
}, 4000); }, 4000);
}, 200) }, 200)
} }

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/08/18 00:53:53 by edbernar #+# #+# */ /* Created: 2024/08/18 00:53:53 by edbernar #+# #+# */
/* Updated: 2024/10/04 21:47:35 by edbernar ### ########.fr */ /* Updated: 2024/10/06 16:04:20 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -164,7 +164,6 @@ class MultiOnlineGamePage
renderer.setAnimationLoop(loop) renderer.setAnimationLoop(loop)
sendRequest('game', {action: 1}); sendRequest('game', {action: 1});
let lastPosition = player.object.position.x; let lastPosition = player.object.position.x;
let lastUp = player.isUp; let lastUp = player.isUp;
interval = setInterval(() => { interval = setInterval(() => {
@ -254,7 +253,10 @@ class MultiOnlineGamePage
let intervalEnd = null; let intervalEnd = null;
let time = 4; let time = 4;
endGameScore.innerText = `${map.score.player} - ${map.score.opponent}`; if (!map)
return ;
if (map && map.score)
endGameScore.innerText = `${map.score.player} - ${map.score.opponent}`;
if (content.won) if (content.won)
scoreText.innerText = "You win !" scoreText.innerText = "You win !"
endGameDiv.style.display = 'flex'; endGameDiv.style.display = 'flex';

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/19 23:08:31 by edbernar #+# #+# */ /* Created: 2024/09/19 23:08:31 by edbernar #+# #+# */
/* Updated: 2024/10/02 13:34:58 by edbernar ### ########.fr */ /* Updated: 2024/10/06 23:50:01 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -51,13 +51,12 @@ class ProfilPage
else else
sendRequest("get_user_info", {id: user}); sendRequest("get_user_info", {id: user});
crossProfil.addEventListener('click', () => { crossProfil.addEventListener('click', () => {
if (typeof(user) == 'string') if (document.precedentPage)
pageRenderer.changePage('homePage'); pageRenderer.changePage(document.precedentPage);
else else
pageRenderer.changePage('lobbyPage'); pageRenderer.changePage('homePage');
}); });
waitForUserInfo().then((userInfo) => { waitForUserInfo().then((userInfo) => {
console.log(userInfo);
if (userInfo == null) if (userInfo == null)
{ {
pageRenderer.changePage('homePage'); pageRenderer.changePage('homePage');
@ -182,12 +181,11 @@ function createGraph(ctx, data)
new Chart(ctx, { new Chart(ctx, {
type: 'pie', type: 'pie',
data: { data: {
labels: ['Win', 'Lose'], labels: [' Win ', ' Lose '],
datasets: [{ datasets: [{
label: 'Couleurs',
data: [data.win, data.lose], data: [data.win, data.lose],
backgroundColor: ['#11ad11', '#E74040'], backgroundColor: ['#11ad11', '#E74040'],
hoverOffset: 4 hoverOffset: 1,
}] }]
}, },
options: { options: {

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/25 17:00:35 by edbernar #+# #+# */ /* Created: 2024/09/25 17:00:35 by edbernar #+# #+# */
/* Updated: 2024/09/30 22:47:54 by edbernar ### ########.fr */ /* Updated: 2024/10/06 17:02:12 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -51,7 +51,7 @@ class settingsPage
interval = setInterval(() => { interval = setInterval(() => {
if (userMeInfo.username != "") if (userMeInfo.username != "")
{ {
loginButton.innerText = userMeInfo.username; loginButton.innerText = userMeInfo.username.length > 8 ? userMeInfo.username.substring(0, 8) + '...' : userMeInfo.username;
clearInterval(interval); clearInterval(interval);
} }
}, 200); }, 200);

View File

@ -3,10 +3,10 @@
/* ::: :::::::: */ /* ::: :::::::: */
/* typeGame.js :+: :+: :+: */ /* typeGame.js :+: :+: :+: */
/* +:+ +:+ +:+ */ /* +:+ +:+ +:+ */
/* By: hubourge <hubourge@student.42.fr> +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/09/15 12:00:01 by edbernar #+# #+# */ /* Created: 2024/09/15 12:00:01 by edbernar #+# #+# */
/* Updated: 2024/09/30 17:11:10 by hubourge ### ########.fr */ /* Updated: 2024/10/06 15:32:02 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -39,7 +39,7 @@ function typeGame(content)
opponent.movePlayer(content); opponent.movePlayer(content);
else if (content.action == 4) else if (content.action == 4)
player.scalePlayer(content.is_opponent); player.scalePlayer(content.is_opponent);
else if (content.action == 5) else if (content.action == 5 && ball)
ball.updatePos(content); ball.updatePos(content);
else if (content.action == 6) else if (content.action == 6)
player.makeAnimation(content.is_opponent); player.makeAnimation(content.is_opponent);

View File

@ -6,7 +6,7 @@
/* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */ /* By: edbernar <edbernar@student.42angouleme. +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */ /* +#+#+#+#+#+ +#+ */
/* Created: 2024/10/01 13:29:50 by edbernar #+# #+# */ /* Created: 2024/10/01 13:29:50 by edbernar #+# #+# */
/* Updated: 2024/10/05 03:02:38 by edbernar ### ########.fr */ /* Updated: 2024/10/06 15:32:04 by edbernar ### ########.fr */
/* */ /* */
/* ************************************************************************** */ /* ************************************************************************** */
@ -57,7 +57,4 @@ function joinTournament(content)
pageRenderer.changePage('tournamentPage', false, content.code); pageRenderer.changePage('tournamentPage', false, content.code);
} }
console.warn("Remove this : window.typeTournament = typeTournament;");
window.typeTournament = typeTournament;
export { typeTournament }; export { typeTournament };