Skip to content

Commit

Permalink
Merge branch 'main' into backend/features/pongbot
Browse files Browse the repository at this point in the history
  • Loading branch information
okbrandon committed Oct 11, 2024
2 parents bcde635 + 3d76555 commit 1e9e546
Show file tree
Hide file tree
Showing 28 changed files with 336 additions and 48 deletions.
19 changes: 11 additions & 8 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -38,27 +38,30 @@ logs: intro ## Show the logs of the project
@ $(DC) logs -f

logs-backend: intro ## Show the logs of the backend
@ docker logs ft_transcendence-backend-1
@ docker logs ft_transcendence-backend-1 -f

logs-frontend: intro ## Show the logs of the frontend
@ docker logs ft_transcendence-frontend-1
@ docker logs ft_transcendence-frontend-1 -f

logs-harvester: intro ## Show the logs of the harvester
@ docker logs ft_transcendence-harvester-1
@ docker logs ft_transcendence-harvester-1 -f

logs-postgres: intro ## Show the logs of the database
@ docker logs ft_transcendence-postgres-1
@ docker logs ft_transcendence-postgres-1 -f

logs-statcruncher: intro ## Show the logs of the statcruncher
@ docker logs ft_transcendence-statcruncher-1

logs-traefik: intro ## Show the logs of the reverse proxy
@ docker logs ft_transcendence-traefik-1
@ docker logs ft_transcendence-statcruncher-1 -f

down: intro ## Stop the project
@ $(DC) down

clean: down ## Stop the project and remove all the stopped containers / unused networks / dangling images / unused build caches (docker system prune -f)
@ docker system prune -f

cleanv: down ## Stop the project and remove all the volumes
@ docker volume prune -af

fclean: cleanv ## Stop the project and remove all the stopped containers / unused networks / dangling images / unused build caches / volumes
@ docker system prune -af

.PHONY: all up down clean
28 changes: 22 additions & 6 deletions backend/api/consumers.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,9 +548,9 @@ async def handle_paddle_move(self, data):
paddle_speed = 5 # Appropriate paddle speed (adjust as needed)

if direction == 'up':
match_state[player_key]['paddle_y'] = min(690, match_state[player_key]['paddle_y'] + paddle_speed)
match_state[player_key]['paddle_y'] = min(682, match_state[player_key]['paddle_y'] + paddle_speed)
elif direction == 'down':
match_state[player_key]['paddle_y'] = max(60, match_state[player_key]['paddle_y'] - paddle_speed)
match_state[player_key]['paddle_y'] = max(73, match_state[player_key]['paddle_y'] - paddle_speed)

# logger.debug(f"[{self.__class__.__name__}] Paddle moved: {player_key} - {direction}")
await self.send_match_update()
Expand Down Expand Up @@ -700,7 +700,7 @@ async def run_match_loop(self, match_id):
PADDLE_WIDTH = 10
PADDLE_HEIGHT = 60
BALL_RADIUS = 25 / 2
BALL_SPEED = 0.3
BALL_SPEED = 0.6
MAX_SCORE = 10

while match_id in self.active_matches:
Expand Down Expand Up @@ -730,11 +730,11 @@ async def run_match_loop(self, match_id):
if match_state['ball']['x'] <= 0:
match_state['scores'][match_state['playerB']['id']] += 1
self.reset_ball(match_state)
logger.info(f"[{self.__class__.__name__}] Player B scored in match: {match_id}")
await self.send_ball_scored(match_state['playerB'])
elif match_state['ball']['x'] + BALL_RADIUS >= TERRAIN_WIDTH:
match_state['scores'][match_state['playerA']['id']] += 1
self.reset_ball(match_state)
logger.info(f"[{self.__class__.__name__}] Player A scored in match: {match_id}")
await self.send_ball_scored(match_state['playerA'])

# Check if game has ended
if match_state['scores'][match_state['playerA']['id']] >= MAX_SCORE or match_state['scores'][match_state['playerB']['id']] >= MAX_SCORE:
Expand All @@ -744,7 +744,7 @@ async def run_match_loop(self, match_id):
break

await self.send_match_update()
await asyncio.sleep(1 / 120) # 120 FPS
await asyncio.sleep(1 / 60) # 120 FPS

async def send_paddle_hit(self, player, ball):
await self.channel_layer.group_send(
Expand All @@ -763,6 +763,22 @@ async def paddle_hit(self, event):
})
logger.info(f"[{self.__class__.__name__}] Paddle hit event sent for player: {event['player']['id']}")

async def send_ball_scored(self, player):
await self.channel_layer.group_send(
f"match_{self.match.matchID}",
{
"type": "ball.scored",
"player": player
}
)

async def ball_scored(self, event):
await self.send_json({
"e": "BALL_SCORED",
"d": {"player": event["player"]}
})
logger.info(f"[{self.__class__}] Ball scored event processed for player: {event['player']['id']}")

def reset_ball(self, match_state):
if self.match.flags & (1 << 1):
dx = random.choice([-8, -7])
Expand Down
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ services:
- certs
ports:
- "8888:443"
- "8000:80"
networks:
- transcendence
volumes:
Expand Down
24 changes: 24 additions & 0 deletions frontend/config/nginx/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,27 @@ server {
proxy_set_header Host $host;
}
}

server {
listen 80;
server_name localhost;

location /api/ {
proxy_pass https://backend:8443;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}

location /ws/ {
proxy_pass https://backend:8443;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
2 changes: 1 addition & 1 deletion frontend/src/api/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export const isRefreshExpired = () => {
};

const API = axios.create({
baseURL: `/api/v1/`,
baseURL: process.env.REACT_APP_ENV === 'production' ? '/api/v1' : 'http://localhost:8000/api/v1',
});

API.interceptors.request.use(
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/api/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import axios from 'axios';

export const ApiLogin = async (username, password, otp) => {
const data = otp ? { username, password, otp } : { username, password };
const response = await axios.post(`/api/v1/auth/login`, data);
const response = await axios.post(process.env.REACT_APP_ENV === 'production' ? '/api/v1/auth/login' : 'http://localhost:8000/api/v1/auth/login', data);
localStorage.setItem('token', response.data.access);
localStorage.setItem('refresh', response.data.refresh);
};

export const ApiSignup = async formData => {
await axios.post(`/api/v1/auth/register`, formData);
await axios.post(process.env.REACT_APP_ENV === 'production' ? '/api/v1/auth/register' : 'http://localhost:8000/api/v1/auth/register', formData);
};
2 changes: 1 addition & 1 deletion frontend/src/api/logger.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const logger = (message) => {
if (process.env.NODE_ENV === "development") {
if (process.env.REACT_APP_ENV === "development") {
console.log(message);
}
};
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/api/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const refreshToken = async () => {
throw new Error("Refresh token expired");
}

const response = await axios.post(`/api/v1/auth/token/refresh`, { refresh });
const response = await axios.post(process.env.REACT_APP_ENV === 'production' ? '/api/v1/auth/token/refresh' : 'http://localhost:8000/api/v1/auth/token/refresh', { refresh });
const newToken = response.data.access;

localStorage.setItem("token", newToken);
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/app/Router.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { isValidToken } from '../api/api';
import Root from '../components/Root';
import SignIn from '../components/Auth/SignIn';
import SignUp from '../components/Auth/SignUp';
import Game from '../components/Game/Game';
import Game from '../components/Game/remote/Game';
import Home from '../components/Home/Home';
import Profile from '../components/Profile/Profile';
import Verify from '../components/Auth/Verify';
Expand All @@ -24,6 +24,7 @@ import Friends from '../components/Friends/Friends';
import PageNotFound from '../components/PageNotFound/PageNotFound';
import Settings from '../components/Settings/Settings';
import { useAuth } from '../context/AuthContext';
import GameLocal from '../components/Game/local/GameLocal';

const PrivateRoutes = () => {
const { isLoggedIn, setIsLoggedIn } = useAuth();
Expand Down Expand Up @@ -73,6 +74,7 @@ const Router = createBrowserRouter(createRoutesFromElements(
<Route element={ <GameRoutes/> }>
<Route path="game" element={ <Game/> }/>
<Route path="playmenu" element={ <PlayMenu/> }/>
<Route path="game-local" element={ <GameLocal/> }/>
</Route>
<Route path="leaderboard" element={ <Leaderboard/> }/>
</Route>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Auth/SignIn.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const SignIn = () => {

const handleFortyTwo = event => {
event.preventDefault();
window.location.href = `/api/v1/auth/42/login`;
window.location.href = process.env.REACT_APP_ENV === 'production' ? '/api/v1/auth/42/login' : 'http://localhost:8000/api/v1/auth/42/login';
};

return (
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/components/Auth/TwoFactorAuthSignIn.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { useTranslation } from "react-i18next";
import axios from "axios";
import { useNotification } from "../../context/NotificationContext";
import { ApiLogin } from "../../api/auth";
import logger from "../../api/logger";
import { useAuth } from "../../context/AuthContext";
import OTPInputComponent from "./OTPInput";
import { FormContainer } from "./styles/Authentication.styled";
Expand All @@ -30,7 +29,7 @@ const TwoFactorAuthSignIn = ({ username, password, setIsTwoFactorAuth, available
}, [otpSent, addNotification, t]);

const handlePlatform = platform => {
axios.post('/api/v1/auth/totp/request', { username, password, platform })
axios.post(process.env.REACT_APP_ENV === 'production' ? '/api/v1/auth/totp/request' : 'http://localhost:8000/api/v1/auth/totp/request', { username, password, platform })
.then(() => {
setOtpSent(true);
})
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Auth/Verify.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const Verify = () => {
const code = params.get('code');

if (code) {
axios.post(`/api/v1/verify`, { code })
axios.post(process.env.REACT_APP_ENV === 'production' ? '/api/v1/verify' : 'http://localhost:8000/api/v1/verify', { code })
.then(() => {
window.location.href = '/signin';
})
Expand Down
9 changes: 5 additions & 4 deletions frontend/src/components/Auth/styles/Authentication.styled.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ export const FormContainer = styled(Form)`
align-items: center;
gap: 20px;
border-radius: 15px;
width: 700px;
padding: 80px 50px;
width: 750px;
padding: 50px 100px;
margin-top: 80px;
font-family: 'Inter', sans-serif;
background: transparent;
Expand All @@ -46,7 +46,7 @@ export const FormContainer = styled(Form)`
& .mb-3 {
width: 100%;
position: relative;
margin: 10px 0;
margin: 20px 0;
& > i {
position: absolute;
Expand Down Expand Up @@ -100,7 +100,7 @@ export const FormContainer = styled(Form)`
.mb-3 input:not(:placeholder-shown) ~ span,
.mb-3 input:invalid ~ span,
.mb-3 input:focus ~ span {
transform: translateX(350px) translateY(-25px);
transform: translateX(400px) translateY(-25px);
font-size: 0.8rem;
padding: 5px 10px;
background: #fff;
Expand Down Expand Up @@ -136,6 +136,7 @@ export const LanguageDropdownButton = styled.select`
font-size: 0.9rem;
font-family: 'Orbitron', sans-serif;
transition: background 0.3s ease, border 0.3s ease;
margin-bottom: 15px;
&:hover {
background: rgba(75, 0, 130, 0.6);
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Friends/FriendsList.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const FriendsList = ({ friends, setIsRefetch }) => {
<ListCard key={key}>
<ProfileInfo onClick={() => handleProfile(friend.username)}>
<ProfileStatus $status={friend.status?.online || false}/>
<ProfileAvatar src={friend.avatarID} alt={`${friend.displayName}'s avatar`}/>
<ProfileAvatar src={friend.avatarID} alt={`${friend.username}'s avatar`}/>
<ProfileInfoContainer>
{friend.displayName}
<ProfileActivity>{setActivityDescription(friend.status?.activity)}</ProfileActivity>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Friends/RequestsList.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ const RequestsList = ({ requests, setIsRefetch }) => {
requests.map((request, key) => (
<ListCard key={key}>
<ProfileInfo onClick={() => handleProfile(request.username)}>
<ProfileAvatar src={request.avatarID} alt={`${request.displayName}'s avatar`}/>
<ProfileAvatar src={request.avatarID} alt={`${request.username}'s avatar`}/>
{request.displayName}
</ProfileInfo>
{request.is === 'sender' ? (
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Game/GameProfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const GameProfile = ({ side, playerSide, player, opponent }) => {
{playerSide === side ? (
player ? (
<>
<ProfileImage src={player.avatarID} alt="Profile Picture"/>
<ProfileImage src={player.avatarID} alt={`${player.username}'s avatar`}/>
<ProfileName>{player.username}</ProfileName>
</>
) : (
Expand All @@ -20,7 +20,7 @@ const GameProfile = ({ side, playerSide, player, opponent }) => {
) : (
opponent ? (
<>
<ProfileImage src={opponent.avatarID} alt="Profile Picture"/>
<ProfileImage src={opponent.avatarID} alt={`${opponent.username}'s avatar`}/>
<ProfileName>{opponent.username}</ProfileName>
</>
) : (
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Game/PlayMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const PlayMenu = () => {
<ModeCard onClick={() => navigate('/game', { state: { mode: '1v1' } })}>
<h1>1 v 1</h1>
</ModeCard>
<ModeCard>
<ModeCard onClick={() => navigate('/game-local')}>
<h1>Local</h1>
</ModeCard>
</ModesContainer>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/Game/Tournament/JoinTournament.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ const JoinTournament = () => {
{activeFriends.length ? (
activeFriends.map((friend) => (
<FriendItem key={friend.userID}>
<FriendProfilePicture src={friend.avatarID} alt={`${friend.displayName}'s avatar`} />
<FriendProfilePicture src={friend.avatarID} alt={`${friend.username}'s avatar`} />
{friend.displayName}
</FriendItem>
))
Expand Down
Loading

0 comments on commit 1e9e546

Please sign in to comment.