Skip to content

Commit

Permalink
FIX:GAME (#90) (#91)
Browse files Browse the repository at this point in the history
  • Loading branch information
automerge-pingpong[bot] authored Nov 14, 2023
2 parents 5435908 + 720e15c commit 3bf1381
Show file tree
Hide file tree
Showing 8 changed files with 187 additions and 1,432 deletions.
51 changes: 35 additions & 16 deletions backend/code/src/game/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class Game {
}

private down2() {
this.eventp2Paddle -= this.p2Res.h / 6 / 6;
this.eventp2Paddle += this.p2Res.h / 6 / 6;
if (this.eventp2Paddle - this.p2Res.h / 6 / 6 < 0) {
this.eventp2Paddle = 0;
}
Expand All @@ -108,32 +108,40 @@ export class Game {
private async loop() {
if (this.closeGame) return;
console.log('loop');
if (this.x + this.ballSize / 2 + this.dx >= this.w || this.x + this.dx <= 0)
if (
this.x + this.dx + this.ballSize / 2 >= this.w ||
this.x + this.dx - this.ballSize / 2 <= 0
)
this.dx *= -1;
if (this.y + this.ballSize / 2 + this.dy >= this.h || this.y + this.dy <= 0)
if (
this.y + this.dy + this.ballSize / 2 >= this.h ||
this.y + this.dy - this.ballSize / 2 <= 0
)
this.dy *= -1;

if (
this.y > this.p1PaddleY &&
this.y < this.p1PaddleY + this.paddleHeight &&
this.x - this.ballSize / 2 < this.paddleWidth + 10
this.x <= this.paddleWidth + this.gap + this.ballSize / 2
) {
this.dx *= -1;
this.dy *= Math.random() * (1.5 - 2.5) + 1.5;
this.dy = Math.random() * (4 - 1.5) + 1.5;
}

if (
this.y > this.p2PaddleY &&
this.y < this.p2PaddleY + this.paddleHeight &&
this.x + this.ballSize / 2 > this.w - (this.paddleWidth + 10)
this.y > this.p1PaddleY &&
this.y < this.p1PaddleY + this.paddleHeight &&
this.x >= this.w - (this.paddleWidth + this.gap + this.ballSize / 2)
) {
this.dx *= -1;
this.dy *= Math.random() * (1.5 - 2.5) + 1.5;
this.dy = Math.random() * (4 - 1.5) + 1.5;
}
if (
(this.y < this.p2PaddleY ||
this.y > this.p2PaddleY + this.paddleHeight) &&
this.x + this.ballSize >= this.w - (this.paddleWidth + 10)
this.x + this.ballSize / 2 >= this.w - (this.paddleWidth + this.gap)
) {
console.log(`${this.p1PaddleY} ${this.x} ${this.y} ${this.ballSize}`);
this.p1Score += 1;
this.init();
this.checkForWinner();
Expand All @@ -142,8 +150,9 @@ export class Game {
if (
(this.y < this.p1PaddleY ||
this.y > this.p1PaddleY + this.paddleHeight) &&
this.x <= this.paddleWidth + 10
this.x - this.ballSize / 2 <= this.paddleWidth + this.gap
) {
console.log(`${this.p1PaddleY} ${this.x} ${this.y} ${this.ballSize}`);
this.p2Score += 1;
this.init();
this.checkForWinner();
Expand All @@ -152,6 +161,10 @@ export class Game {

console.log(this.x);
console.log(this.y);
// const forwardx = this.x + this.dx;
// const forwardy = this.y + this.dy
// if (forwardx > this.) {
// }
this.x += this.dx;
this.y += this.dy;

Expand Down Expand Up @@ -205,7 +218,7 @@ export class Game {
);
}

await this.sleep(25);
await this.sleep(this.frames);

this.loop();
}
Expand Down Expand Up @@ -241,6 +254,9 @@ export class Game {
console.log(p2Data);
this.server.emit('players', [p1Data, p2Data]);
console.log('newfunc');
setInterval(() => {
this.frames -= 1;
}, 2000);
this.p1socket.on('up', () => {
this.up1();
});
Expand Down Expand Up @@ -342,23 +358,26 @@ export class Game {
this.x = this.w / 2;
this.y = this.h / 2;
this.ballSize = this.w / 42;
this.dx = Math.random() > 0.5 ? this.w / 200 : (this.w / 200) * -1;
this.dy = Math.random() > 0.5 ? this.w / 200 : (this.w / 200) * -1;
this.dx = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
this.dy = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
this.p1PaddleY = this.h / 2;
this.p2PaddleY = this.h / 2;
this.frames = 25;
}
private gameid: string;
private p1socket: Socket;
private p2socket: Socket;
private p1Data: any;
private p2Data: any;
private frames: number = 25;
private w: number = 1067;
private h: number = 600;
private x: number = this.w / 2;
private y: number = this.h / 2;
private gap: number = this.w / 100;
private ballSize: number = this.w / 42;
private dx: number = Math.random() > 0.5 ? this.w / 200 : (this.w / 200) * -1;
private dy: number = Math.random() > 0.5 ? this.w / 200 : (this.w / 200) * -1;
private dx: number = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
private dy: number = Math.random() > 0.5 ? this.w / 220 : (this.w / 220) * -1;
private p1PaddleY: number = this.h / 2;
private p2PaddleY: number = this.h / 2;
private eventp1Paddle: number = 0;
Expand Down
1 change: 1 addition & 0 deletions docker-compose-dev.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ services :
networks:
- pongnet
backend:
container_name: backend
build:
context: ./backend
dockerfile: Dockerfile.dev
Expand Down
118 changes: 99 additions & 19 deletions frontend/code/src/Api/base.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import axios from "axios";
// const navigate = useNavigate();
// return navigate;
// };
const api = axios.create({

const apiWithoutManager = axios.create({
baseURL: `${process.env.REACT_APP_API_ENDPOINT}`,
timeout: 10000,
withCredentials: true,
Expand All @@ -15,26 +16,105 @@ const api = axios.create({
},
});

let refreshAttempted = 0;

const errorHandler = async (error: any) => {

if (error?.response?.status === 401) {
if (refreshAttempted <= 2) {
const ConcurrencyManager = (axios: any, MAX_CONCURRENT = 10) => {
if (MAX_CONCURRENT < 1){
//eslint-disable-next-line
throw "Concurrency Manager Error: minimun concurrent requests is 1";
}
let instance = {
queue: [] as any[],
running: [] as any[],
shiftInitial: () => {
setTimeout(() => {
if (instance.running.length < MAX_CONCURRENT) {
instance.shift();
}
}, 0);
},
push: (reqHandler: any) => {
instance.queue.push(reqHandler);
instance.shiftInitial();
},
shift: () => {
if (instance.queue.length) {
const queued = instance.queue.shift();
queued.resolver(queued.request);
instance.running.push(queued);
}
},
// Use as interceptor. Queue outgoing requests
requestHandler: (req: any) => {
return new Promise(resolve => {
instance.push({ request: req, resolver: resolve });
});
},
// Use as interceptor. Execute queued request upon receiving a response
responseHandler: (res: any) => {
instance.running.shift();
instance.shift();
return res;
},
responseErrorHandler: async (error: any) => {
if (error?.response?.status === 401) {
try {
refreshAttempted++;
await api.get("auth/refresh");
return api.request(error.config);
} catch (refreshError) {}
} else {
refreshAttempted--;
const refreshError = await apiWithoutManager.get("auth/refresh").then(() => null).catch((err: any) => err);
if (refreshError && window.location.pathname !== '/') {
instance.queue = [];
instance.running = [];
window.location.href = '/';
return;
}
const res = await apiWithoutManager.request(error.config);
return instance.responseHandler(res);
} catch (refreshError) { }
}
return Promise.reject(instance.responseHandler(error));
},
interceptors: {
request: null,
response: null
},
detach: () => {
axios.interceptors.request.eject(instance.interceptors.request);
axios.interceptors.response.eject(instance.interceptors.response);
}
return Promise.reject(error);
};
api.interceptors.response.use(
(response) => response,
(error) => errorHandler(error)
// queue concurrent requests
instance.interceptors.request = axios.interceptors.request.use(
instance.requestHandler
);

export default api;
instance.interceptors.response = axios.interceptors.response.use(
instance.responseHandler,
instance.responseErrorHandler,
);
return instance;
};

const api = axios.create({
baseURL: `${process.env.REACT_APP_API_ENDPOINT}`,
timeout: 10000,
withCredentials: true,
headers: {
"Cache-Control": "no-cache",
"Content-Type": "application/json",
},
});

// init your manager.
ConcurrencyManager(api, 1);

// const errorHandler = async (error: any) => {
// if (error?.response?.status === 401) {
// try {
// await api.get("auth/refresh");
// return api.request(error.config);
// } catch (refreshError) {}
// }
// return Promise.reject(error);
// };
// api.interceptors.response.use(
// (response) => response,
// (error) => errorHandler(error)
// );

export default api;
85 changes: 48 additions & 37 deletions frontend/code/src/Components/Chat/Services/SocketsServices.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,54 @@
import { io } from 'socket.io-client';
import { create } from 'zustand'

interface SocketStore {
socket: any;
connected: boolean;

const reconnect = () => {
return io("http://localhost:3004", {
transports: ['websocket'],
});
setSocket: () => any;
}
export const useSocketStore:any = create((set:any) => ({
socket:null,
connected:false,
setSocket : () => {

var s:any;

const soc = set((state:any) => {
if (state.socket === null){
s = io("http://localhost:3004", {
transports: ['websocket'],
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax' : 1000,
'reconnectionAttempts': 5
});


s.on('connect_error', async() => {
await new Promise(r => setTimeout((r) => {
console.log("inside");
s = reconnect();
s.on('connect' , () => {console.log("connected")}
)
},1000))
});
return {socket:s}
}
return state
})
return soc ? soc : s;

}}))

export const useSocketStore = create<SocketStore>((set, get) => ({
socket: null,
connected: false,
setSocket: () => {
let newSocket: any = null;

set((state) => {
if (state.socket === null) {
newSocket = io("http://localhost:3004", {
transports: ['websocket'],
'reconnection': true,
'reconnectionDelay': 1000,
'reconnectionDelayMax': 1000,
'reconnectionAttempts': 5
});

// Set socket
set({ ...state, socket: newSocket });

newSocket.on('connect', () => {
console.log('Connected!');
// Set connected state
set({ ...state, connected: true });
});

newSocket.on('connect_error', async () => {
await new Promise((resolve) => setTimeout(() => {
// Set connected state
set({ ...state, connected: false });
newSocket.connect();
resolve(newSocket);
}, 1000))
});

return { ...state, socket: newSocket };
}

return state;
});

return newSocket;
}
}))

6 changes: 3 additions & 3 deletions frontend/code/src/Components/Game/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useGameState } from "./States/GameState";
import { useSocketStore } from "../Chat/Services/SocketsServices";
import { useNavigate } from "react-router-dom";

const DURATION = 25;
const DURATION = 20;
type Cords = {
x:number;
y:number;
Expand Down Expand Up @@ -151,8 +151,8 @@ export const Game = () => {
<Layer >
<Rect height={gameState.height} width={gameState.width} fill="#151B26" x={0} y={0} />
<Line points={[0, gameState.height , 0 , 0]} dash={[gameState.height / 30 , 10]} strokeWidth={2} stroke={"white"} height={gameState.height} width={20} fill="white" x={gameState.width / 2} y={0} />
<Rect cornerRadius={12} height={gameState.height / 6} width={gameState.width / 70} x={10} y={gameState.lPaddle} fill="white" />
<Rect cornerRadius={12} height={gameState.height / 6} width={gameState.width / 70} x={gameState.width - 10 - (gameState.width / 70)} y={gameState.rPaddle} fill="white" />
<Rect cornerRadius={12} height={gameState.height / 6} width={gameState.width / 70} x={gameState.width / 100} y={gameState.lPaddle} fill="white" />
<Rect cornerRadius={12} height={gameState.height / 6} width={gameState.width / 70} x={gameState.width - (gameState.width / 100) - (gameState.width / 70)} y={gameState.rPaddle} fill="white" />
<Circle fill="white" height={gameState.ball.size} width={gameState.ball.size} x={gameState.ball.x} y={gameState.ball.y} />
</Layer>

Expand Down
2 changes: 1 addition & 1 deletion nginx/default.conf
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ server {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;

proxy_pass http://backend:3001;
proxy_pass http://backend:3004;

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
Expand Down
Loading

0 comments on commit 3bf1381

Please sign in to comment.