Skip to content

Commit

Permalink
confirmation modal does not appear at theendof game anymore
Browse files Browse the repository at this point in the history
  • Loading branch information
trsctr committed Aug 23, 2024
1 parent 163b244 commit a0f39d5
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 98 deletions.
138 changes: 42 additions & 96 deletions Frontend/src/js/modals/playonline.js
Original file line number Diff line number Diff line change
@@ -1,71 +1,62 @@
import * as bootstrap from 'bootstrap';
import { startGame } from '../pong/pong';

const pongModal = new bootstrap.Modal(document.getElementById('pongModal')); // Peli modalin määrittely
var waitingLobbyModalLabel = document.getElementById('waitingLobbyModalLabel');
var lobbyContent = document.getElementById('lobbyContent')
var waitingLobbyModal = new bootstrap.Modal(document.getElementById('waitingLobbyModal'));
const pongModalElement = document.getElementById('pongModal');
const waitingLobbyModalElement = document.getElementById('waitingLobbyModal');
const waitingLobbyModalLabel = document.getElementById('waitingLobbyModalLabel');
const lobbyContent = document.getElementById('lobbyContent');

// Initialize modals
const pongModal = new bootstrap.Modal(pongModalElement);
const waitingLobbyModal = new bootstrap.Modal(waitingLobbyModalElement);

// Function to open the waiting lobby
export function openWaitingLobby() {
waitingLobbyModal.show();

lobbyContent.innerHTML =
`<div class="d-flex justify-content-center">
<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
<span class="visually-hidden">Waiting for players...</span>
</div>
</div>
`
waitingLobbyModalLabel.textContent = "Waiting for players.."
</div>`;
waitingLobbyModalLabel.textContent = "Waiting for players..";

//document.getElementById('startGameButton').addEventListener('click', startRemoteGame);
// Simulate a call to the server to find other players
setTimeout(() => {
connectToWebSockets();
}, 1000);

// searchForPlayers();
}

function connectToWebSockets() {

const userData = JSON.parse(sessionStorage.getItem('userData'));
if (!userData || !userData.token) {
console.error('User data or token is missing');
return;
}

// Connect to the online status WebSocket
const onlineStatusSocket = new WebSocket(`/ws/online/?token=${userData.token}`);

let gameRoomSocket;

// Setup WebSocket event handlers for online status
onlineStatusSocket.onopen = function() {

console.log('Connected to online status WebSocket');
};

onlineStatusSocket.onmessage = function(event) {
const data = JSON.parse(event.data);
if (data.type === 'wait_for_opponent') {
// Room has been assigned, connect to the game room WebSocket
const roomName = data.room_name;
connectToGameRoom(roomName);
}
else if (data.type === 'match_found')
{
} else if (data.type === 'match_found') {
const roomName = data.room_name;
connectToGameRoom(roomName);
connectToGameRoom(roomName);
lobbyContent.innerHTML =
`<div class="d-flex justify-content-center">
<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
<span class="visually-hidden">Match found! Connecting..</span>
</div>
</div>
`
waitingLobbyModalLabel.textContent = "Match found! Connecting.."
</div>`;
waitingLobbyModalLabel.textContent = "Match found! Connecting..";
}
};

Expand All @@ -77,50 +68,44 @@ function connectToWebSockets() {
console.error('Error in online status WebSocket:', error);
};

// Function to connect to the game room WebSocket
function connectToGameRoom(roomName) {
gameRoomSocket = new WebSocket(`/ws/game/room/${roomName}/?token=${userData.token}`);

gameRoomSocket.onopen = function() {
console.log(`Connected to game room ${roomName} WebSocket`);
// Notify server that the user has joined the room
gameRoomSocket.send(JSON.stringify({ type: 'join', username: userData.username }));
};

gameRoomSocket.onmessage = function(event) {
const data = JSON.parse(event.data);
console.log('Received from game room WebSocket:', data);
if (data.type === 'starting_game') {
lobbyContent.innerHTML =
`<div class="d-flex justify-content-center">
<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
<span class="visually-hidden">Match found! Connecting..</span>
</div>
`<div class="d-flex justify-content-center">
<div class="spinner-border" style="width: 4rem; height: 4rem;" role="status">
<span class="visually-hidden">Starting game..</span>
</div>
`

waitingLobbyModalLabel.textContent = "Starting game.."

</div>`;
waitingLobbyModalLabel.textContent = "Starting game..";

let config = {
isRemote: true,
gameId: data.message.game_id,
playerIds: [ data.message.player1_id, data.message.player2_id ],
playerIds: [data.message.player1_id, data.message.player2_id],
player1Alias: data.message.player1_username,
player2Alias: data.message.player2_username,
isLocalTournament: false,
}
// Close the waiting lobby modal
};

// Close the online status WebSocket
if (onlineStatusSocket.readyState === WebSocket.OPEN) {
onlineStatusSocket.close();
}

// Close the game room WebSocket if it exists and is open
if (gameRoomSocket && gameRoomSocket.readyState === WebSocket.OPEN) {
gameRoomSocket.close();
}

pongModal.show();
waitingLobbyModal.hide();
startGame('pongGameContainer', config, handleGameEnd);
}
};
Expand All @@ -133,25 +118,22 @@ function connectToWebSockets() {
console.error(`Error in game room ${roomName} WebSocket:`, error);
};
}
var waitingLobbyModal = document.getElementById('waitingLobbyModal');
waitingLobbyModal.addEventListener('hide.bs.modal', function () {
console.log('Modal is closing. Disconnecting WebSockets.');

// Close the online status WebSocket
waitingLobbyModalElement.addEventListener('hide.bs.modal', function () {
console.log('Modal is closing. Disconnecting WebSockets.');
if (onlineStatusSocket.readyState === WebSocket.OPEN) {
onlineStatusSocket.close();
}

// Close the game room WebSocket if it exists and is open
if (gameRoomSocket && gameRoomSocket.readyState === WebSocket.OPEN) {
gameRoomSocket.close();
}
});
}

function handleGameEnd(data) {
// Update the game history record with the winner_id
pongModal.hide();
waitingLobbyModal.show();
const userData = JSON.parse(sessionStorage.getItem('userData'));
if (!userData || !userData.token) {
console.error('User data or token is missing');
Expand All @@ -163,14 +145,13 @@ function handleGameEnd(data) {
.then(gameHistoryRecord => {
lobbyContent.innerHTML = `<p>Final Score:</p>
<p>${gameHistoryRecord.player1_username}: ${data.player1_score}</p>
<p>${gameHistoryRecord.player2_username}: ${data.player2_score}</p>
`
if (Number(userData.id) === data.winner){
<p>${gameHistoryRecord.player2_username}: ${data.player2_score}</p>`;
if (Number(userData.id) === data.winner) {
updateGameHistory(data, gameHistoryRecord);
}
});
setTimeout(() => {
waitingLobbyModal.hide()
waitingLobbyModal.hide();
}, 5000);
}

Expand All @@ -179,26 +160,24 @@ function updateGameHistory(data, gameHistoryRecord) {
fetch(`/game-history/${data.game_id}/`)
.then(response => response.json())
.then(gameHistoryRecord => {
// Update the winner_id field
if (gameHistoryRecord.winner_id === data.winner) {
console.log(gameHistoryRecord)
console.log(gameHistoryRecord);
return;
}
else
} else {
gameHistoryRecord.winner_id = data.winner;
return fetch(`/game-history/${data.game_id}/`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(gameHistoryRecord)
});
return fetch(`/game-history/${data.game_id}/`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(gameHistoryRecord)
});
}
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Create the game statistics record
const gameStatData = {
game_id: data.game_id,
player1_score: data.player1_score,
Expand Down Expand Up @@ -228,36 +207,3 @@ function updateGameHistory(data, gameHistoryRecord) {
console.error('Error:', error);
});
}

// Function to start the remote game
export function startRemoteGame(gameId, playerIds) {
const pongModalElement = document.getElementById('pongModal');

// Check if pongModal is initialized
if (!window.pongModal) {
console.error('Pong modal is not initialized.');
return;
}

// Validate input
if (!gameId || !playerIds || playerIds.length !== 2) {
console.error('Invalid game ID or player IDs.');
return;
}

const config = {
gameId: parseInt(gameId, 10),
playerIds: playerIds.map(id => parseInt(id, 10)),
isRemote: true,
isLocalTournament: false
};

console.log('Starting remote game with config:', config);

// Start the game with the provided configuration
startGame('pongGameContainer', config);

// Show the Pong modal
window.pongModal.show();
}

1 change: 1 addition & 0 deletions Frontend/src/js/pong/globalState.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ export const globalState = {
glitchPass: null,
view2D: false,
dataSent: false,
globalState: null,
}
4 changes: 2 additions & 2 deletions Frontend/src/js/pong/pong.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ document.addEventListener('DOMContentLoaded', () => {
// }

const bypassConfirmationModal = initializeConfirmationModal('pongModal', title, message);

globalState.bypassConfirmationModal = bypassConfirmationModal;
// test bypassing the confirmation modal
// document.addEventListener('keydown', function(event) {
// if (event.key === 'Backspace') {
Expand Down Expand Up @@ -295,7 +295,7 @@ export function endGame() {

gameStarted = false;
sessionStorage.setItem('isGameOver', 'true');

globalState.bypassConfirmationModal();
console.log("EndGame complete, gameStarted:", gameStarted, "isGameOver:", sessionStorage.getItem('isGameOver'));


Expand Down

0 comments on commit a0f39d5

Please sign in to comment.