From 921048c969b06c59e56d6da9a11508aba0bacfea Mon Sep 17 00:00:00 2001 From: Hepatica Date: Sat, 24 Feb 2024 00:26:39 +0100 Subject: [PATCH] Working on jackpot --- .../css/PagesStyles/games-pages/jackpot.css | 5 + luckydiamond/src/assets/js/chat/ChatLogic.js | 6 + .../src/assets/js/jackpot/JackpotLogic.js | 55 +++++ .../src/components/DevelopComponent.vue | 4 +- .../src/pages/games-pages/JackpotPage.vue | 221 ++++++++++++++++-- luckydiamond/src/properties/Сonfig.js | 2 + 6 files changed, 272 insertions(+), 21 deletions(-) create mode 100644 luckydiamond/src/assets/js/jackpot/JackpotLogic.js diff --git a/luckydiamond/src/assets/css/PagesStyles/games-pages/jackpot.css b/luckydiamond/src/assets/css/PagesStyles/games-pages/jackpot.css index 003c686..cc768c2 100644 --- a/luckydiamond/src/assets/css/PagesStyles/games-pages/jackpot.css +++ b/luckydiamond/src/assets/css/PagesStyles/games-pages/jackpot.css @@ -133,6 +133,11 @@ font-size: 14px; /* Smaller text size for 'БАНК' */ } +.progress-text { + transition: opacity 0.5s ease; + opacity: 1; +} + .progress-bar { width: 95%; background-color: #D9D9D9; /* Navy blue background */ diff --git a/luckydiamond/src/assets/js/chat/ChatLogic.js b/luckydiamond/src/assets/js/chat/ChatLogic.js index 0bbece7..9dea039 100644 --- a/luckydiamond/src/assets/js/chat/ChatLogic.js +++ b/luckydiamond/src/assets/js/chat/ChatLogic.js @@ -8,6 +8,12 @@ let webSocket; export function ConnectToChat() { try { + + if (webSocket && webSocket.readyState === WebSocket.OPEN) { + console.log('WebSocket connection already established.'); + return; + } + webSocket = new WebSocket(BackendWebSocketUrl); webSocket.onopen = function () { diff --git a/luckydiamond/src/assets/js/jackpot/JackpotLogic.js b/luckydiamond/src/assets/js/jackpot/JackpotLogic.js new file mode 100644 index 0000000..2d0242e --- /dev/null +++ b/luckydiamond/src/assets/js/jackpot/JackpotLogic.js @@ -0,0 +1,55 @@ +import { BackendWebSocketJackpotUrl } from '@/properties/Сonfig.js'; +import { eventBus } from "@/main"; + +// import { +// GetCookie +// } from "@/assets/js/storage/CookieStorage.js"; + +let webSocket; + +export function ConnectToJackpotSocket() { + try { + + if (webSocket && webSocket.readyState === WebSocket.OPEN) { + console.log('WebSocket connection already established.'); + return; + } + + webSocket = new WebSocket(BackendWebSocketJackpotUrl); + + webSocket.onopen = function () { + console.log('Connection established'); + }; + + webSocket.onmessage = function (event) { + + // const dataObject = JSON.parse(event.data); + + eventBus.emit('jackpotGameTik', event.data); + + // console.log(dataObject) + // if (dataObject && Object.prototype.hasOwnProperty.call(dataObject, 'SpUserName') && Object.prototype.hasOwnProperty.call(dataObject, 'Message')) { + // eventBus.emit('dataChat', event.data); + // console.log('CHAT') + // } + // else { + // eventBus.emit('crash', event.data) + // } + + }; + + webSocket.onclose = function () { + + webSocket = new WebSocket(BackendWebSocketJackpotUrl); + + console.log('Connection closed and reconnected'); + }; + + webSocket.onerror = function (event) { + webSocket = new WebSocket(BackendWebSocketJackpotUrl); + console.error('WebSocket Error:', event); + }; + } catch (error) { + console.error('Error in ConnectToChat:', error); + } +} diff --git a/luckydiamond/src/components/DevelopComponent.vue b/luckydiamond/src/components/DevelopComponent.vue index 7f773bd..812a516 100644 --- a/luckydiamond/src/components/DevelopComponent.vue +++ b/luckydiamond/src/components/DevelopComponent.vue @@ -55,7 +55,7 @@
-

Бэкендер

+

Фронтэндер

Ckutls_

@@ -130,7 +130,7 @@
-

фронтэндер

+

Фронтэндер

busha888

diff --git a/luckydiamond/src/pages/games-pages/JackpotPage.vue b/luckydiamond/src/pages/games-pages/JackpotPage.vue index 74f3fd9..b7876e2 100644 --- a/luckydiamond/src/pages/games-pages/JackpotPage.vue +++ b/luckydiamond/src/pages/games-pages/JackpotPage.vue @@ -117,10 +117,16 @@
-
15.00 СЕК
+
+ {{ + remainingSeconds >= 0 ? remainingSeconds + " СЕК" : "" + }} +
-
@@ -130,21 +136,23 @@
@@ -175,10 +183,14 @@ import "@/assets/css/PagesStyles/games-pages/jackpot.css"; import "@/assets/css/global.css"; import JackpotNumbers from "@/mocks/JackpotNumbers"; +import { ConnectToJackpotSocket } from "@/assets/js/jackpot/JackpotLogic.js"; + import { Carousel, Slide } from "vue3-carousel"; import "vue3-carousel/dist/carousel.css"; +import { eventBus } from "@/main"; + // import ProgressBar from "vue-bulma-progress-bar"; // import '@/assets/css/PagesStyles/games-pages/jackpot.css' @@ -192,32 +204,203 @@ export default { // Pagination // ProgressBar, }, + inject: ["eventBus"], data() { return { JackpotNumbers, - // clickedBtn: null, - // ErrorClick: false, - // ErrorJoin: false, - // balance: 0, + autoplay: 0, + slides: [ + { + img: "https://avatar.spworlds.ru/face/55/Ckutls_.png", + nickname: "Ckutls_", + }, + { + img: "https://avatar.spworlds.ru/face/55/Ckutls_.png", + nickname: "Ckutls_", + }, + { + img: "https://avatar.spworlds.ru/face/55/Ckutls_.png", + nickname: "Ckutls_", + }, + { + img: "https://avatar.spworlds.ru/face/55/Ckutls_.png", + nickname: "Ckutls_", + }, + { + img: "https://avatar.spworlds.ru/face/55/Ckutls_.png", + nickname: "Ckutls_", + }, + { + img: "https://avatar.spworlds.ru/face/55/Ckutls_.png", + nickname: "Ckutls_", + }, + { + img: "https://avatar.spworlds.ru/face/55/Hepatir.png", + nickname: "Hepatir", + }, + ], + currentSlide: 0, value: 0, max: 100, amountDeposit: 0, - - // crashObject: '', - // textError: '', - // startGame: false, - // offBtn: false + isCarouselStopped: false, + targetNickname: "", + isStopButtonPressed: false, + isGameTimerStarted: false, + remainingSeconds: 0, + progressBarWidth: 0, + // idCurrentGame: "", + lastUserWinner: "", + // lastIdGame: "", }; }, + methods: { + checkGameEnd(endGameUtc) { + const endTime = new Date(endGameUtc).getTime(); + const currentTime = new Date().getTime(); + const timeLeft = endTime - currentTime; + + if (timeLeft > 0) { + // Устанавливаем таймер, который сработает, когда игра должна закончиться + setTimeout(() => { + eventBus.emit("gameEnded"); // Транслируем событие окончания игры + console.log("Game has ended"); + }, timeLeft); + } else { + // Игра уже закончилась + // eventBus.emit("gameEnded"); // Транслируем событие окончания игры + console.log("Game has already ended"); + } + }, startAutoScroll() { this.interval = setInterval(() => { this.$refs.carousel.next(); }, 1); }, + startGameTimer(startGameUtc) { + if (!this.isGameTimerStarted) { + this.isGameTimerStarted = true; + const startTime = new Date(startGameUtc).getTime(); + const updateTimer = () => { + const currentTime = new Date().getTime(); + const diff = startTime - currentTime; + this.remainingSeconds = Math.max(0, Math.floor(diff / 1000)); + if (diff <= 0) { + this.remainingSeconds = 0; + this.progressBarWidth = 100; // Полный прогресс + clearInterval(this.timerInterval); // Остановить таймер + this.autoplay = 20; + + // Действия после окончания таймера, если необходимо + } else { + this.remainingSeconds = Math.floor(diff / 1000); // Обновляем оставшееся время в секундах + const totalDuration = 30; // Допустим, обратный отсчет идет с 60 секунд + this.progressBarWidth = + ((totalDuration - this.remainingSeconds) / totalDuration) * 100; + } + + // Обновление текста и ширины прогресс-бара + const progressBarElement = document.querySelector(".progress"); + if (progressBarElement) { + const progressText = + progressBarElement.querySelector(".progress-text"); + if (progressText) { + progressText.style.opacity = "0"; + setTimeout(() => { + progressBarElement.style.width = `${this.progressBarWidth}%`; + progressText.textContent = `${this.remainingSeconds} СЕК`; + progressText.style.opacity = "1"; + }, 500); // Задержка должна соответствовать продолжительности анимации + } + } + }; + + // Запускаем таймер + this.timerInterval = setInterval(updateTimer, 1000); + updateTimer(); // Вызываем сразу для инициализации + } + }, + handleSlideStart(data) { + try { + const { slidingToIndex } = data; + this.currentSlideIndex = slidingToIndex; + if (this.isStopButtonPressed) { + if ( + this.slides[this.currentSlideIndex].nickname === + this.targetNickname && + !this.isCarouselStopped + ) { + this.stopAutoplay(); + } + } + } catch (error) { + console.error("Error in handleSlideStart:", error); + // Здесь вы можете обработать ошибку, например, остановить карусель + } + }, + stopCarousel() { + this.isStopButtonPressed = true; + this.autoplay = 200; + }, + stopAutoplay() { + this.autoplay = 0; + this.isCarouselStopped = true; + if (this.interval) { + clearInterval(this.interval); + } + }, + changeLastFiveImages() { + const newImage = "https://avatar.spworlds.ru/face/55/Hepatir.png"; + console.log(this.slides); + this.slides[9].img = newImage; + }, + stopOnTarget(targetNickname) { + if (this.slides[this.currentSlide].nickname === targetNickname) { + this.autoplay = 0; // Остановить автопрокрутку + return true; // Возвращаем true, если нашли нужный слайд + } + return false; // Возвращаем false, если нужный слайд не найден + }, }, mounted() { - this.startAutoScroll(); + ConnectToJackpotSocket(); + eventBus.on("jackpotGameTik", (data) => { + try { + if (data) { + const dataObject = JSON.parse(data); + console.log(dataObject); + + this.lastUserWinner=dataObject.LastGame.WinnerUserName; + + if (dataObject.CurrentGame.GameState == "StartGameTimer") { + this.startGameTimer(dataObject.CurrentGame.StartGameUtc); + } + + if ( + dataObject.CurrentGame.GameState != "WaitingForPlayers" && + dataObject.CurrentGame.GameState == "Running" + ) { + this.checkGameEnd(dataObject.CurrentGame.EndGameUtc); + // this.idCurrentGame = dataObject.CurrentGame.Id; + } + // Дальнейшая обработка dataObject... + } else { + // Если данные не определены или пусты, выводим соответствующее сообщение в консоль + console.log("Received undefined or null data"); + } + // console.log(dataFromServer); + } catch (error) { + console.log(error); + } + }); + eventBus.on("gameEnded", () => { + setTimeout(() => { + this.targetNickname = this.lastUserWinner; + this.stopCarousel(); + }, 2000); + }); + // this.startAutoScroll(); }, watch: { amountDeposit(DepositCount) { diff --git a/luckydiamond/src/properties/Сonfig.js b/luckydiamond/src/properties/Сonfig.js index 375f3b8..04955cb 100644 --- a/luckydiamond/src/properties/Сonfig.js +++ b/luckydiamond/src/properties/Сonfig.js @@ -1,5 +1,7 @@ export const BackendApiUrl = 'https://spsystemcore20231122004605.azurewebsites.net/api'; export const BackendWebSocketUrl = 'wss://spsystemcore20231122004605.azurewebsites.net'; + +export const BackendWebSocketJackpotUrl = 'wss://spsystemcore20231122004605.azurewebsites.net/jackpot'; // export const BackendApiUrl = 'https://localhost:7062/api'; \ No newline at end of file