";
topWindow.bottomPanel.id = 'client-bottom-panel';
topWindow.bottomBlock.appendChild(topWindow.bottomPanel);
topWindow.playerPanel = document.createElement('div');
topWindow.playerPanel.id = 'client-player-panel';
topWindow.playerPanel.nickContainer = document.createElement('div');
topWindow.playerPanel.nickContainer.id = "client-player-panel-nick-container";
topWindow.playerPanel.nickContainer.style.padding = "3px";
topWindow.playerPanel.indicator = document.createElement('div');
topWindow.playerPanel.indicator.id = "client-player-panel-indicator";
topWindow.playerPanel.nickContainer.appendChild(topWindow.playerPanel.indicator);
topWindow.playerPanel.nickInput = document.createElement('input');
topWindow.playerPanel.nickInput.className = "pquiz-input";
topWindow.playerPanel.nickInput.id = "client-player-panel-nick-input";
topWindow.playerPanel.nickInput.addEventListener('change',()=>{
setPlayerNick( topWindow.playerPanel.nickInput.value);
});
topWindow.playerPanel.nickContainer.appendChild(topWindow.playerPanel.nickInput);
topWindow.playerPanel.nickButton = document.createElement('button');
topWindow.playerPanel.nickButton.className = "pquiz-button";
topWindow.playerPanel.nickButton.id = "client-player-panel-nick-btn";
topWindow.playerPanel.nickButton.innerHTML = "УЧАСТВУЮ >>>";
topWindow.playerPanel.nickButton.addEventListener('click', ()=> {
topWindow.player.state = "AWRG";
updateAnswerBtns("AWRG");
sendPlayerState();
});
topWindow.playerPanel.nickContainer.appendChild(topWindow.playerPanel.nickButton);
topWindow.playerPanel.appendChild(topWindow.playerPanel.nickContainer);
topWindow.playerPanel.answerBtnContainer = document.createElement('div');
topWindow.playerPanel.answerBtnContainer.id = "client-player-panel-answer-btn-container";
topWindow.playerPanel.answerBtnContainer.style.marginTop = '8px';
topWindow.playerPanel.answerBtnReady = document.createElement('div');
topWindow.playerPanel.answerBtnReady.innerHTML = "ОТВЕТ";
topWindow.playerPanel.answerBtnReady.style.borderRadius = "12px 0 0 12px";
topWindow.playerPanel.answerBtnReady.style.marginLeft = "8px";
topWindow.playerPanel.answerBtnReady.className = "client-player-panel-answer-btn";
topWindow.playerPanel.answerBtnReady.addEventListener("click", () => {updateAnswerBtns('ANSW')});
topWindow.playerPanel.answerBtnContainer.appendChild(topWindow.playerPanel.answerBtnReady);
topWindow.playerPanel.answerBtnWait = document.createElement('div');
topWindow.playerPanel.answerBtnWait.innerHTML = "ЖДУ";
topWindow.playerPanel.answerBtnWait.className = "client-player-panel-answer-btn";
topWindow.playerPanel.answerBtnWait.addEventListener("click", () => {updateAnswerBtns('WAIT')});
topWindow.playerPanel.answerBtnContainer.appendChild(topWindow.playerPanel.answerBtnWait);
topWindow.playerPanel.answerBtnPass = document.createElement('div');
topWindow.playerPanel.answerBtnPass.innerHTML = "ПАС";
topWindow.playerPanel.answerBtnPass.style.borderRadius = "0 12px 12px 0";
topWindow.playerPanel.answerBtnPass.className = "client-player-panel-answer-btn";
topWindow.playerPanel.answerBtnPass.addEventListener("click", () => {updateAnswerBtns('PASS')});
topWindow.playerPanel.answerBtnContainer.appendChild(topWindow.playerPanel.answerBtnPass);
topWindow.playerPanel.answerBtnSend = document.createElement('button');
topWindow.playerPanel.answerBtnSend.disabled = true;
topWindow.playerPanel.answerBtnSend.className = "pquiz-button";
topWindow.playerPanel.answerBtnSend.innerHTML = "ОТПРАВИТЬ>>";
topWindow.playerPanel.answerBtnSend.style.margin = "0 0 0 16px";
topWindow.playerPanel.answerBtnSend.addEventListener('click', sendPlayerState);
topWindow.playerPanel.answerBtnContainer.appendChild(topWindow.playerPanel.answerBtnSend);
topWindow.playerPanel.appendChild(topWindow.playerPanel.answerBtnContainer);
topWindow.playerPanel.answerTextArea = document.createElement('textarea');
topWindow.playerPanel.answerTextArea.id = "client-player-panel-answer-textarea";
topWindow.playerPanel.answerTextArea.addEventListener('change', ()=>{
topWindow.player.answer = topWindow.playerPanel.answerTextArea.value;
});
topWindow.playerPanel.answerBtnContainer.appendChild(topWindow.playerPanel.answerTextArea);
topWindow.bottomBlock.appendChild(topWindow.playerPanel);
topWindow.cBlock.appendChild(topWindow.bottomBlock);
topWindow.uBlock = document.querySelector('#client-update-progress-bar');
topWindow.w2gRightBlock = document.querySelector("#w2g-right");
document.querySelector('#client-bottom-panel-update-time').innerHTML = '00:00:00';
document.querySelector('#update-data-button').addEventListener('click', () => {
loadTopData();
gameStateUpdater.counter = gameStateUpdater.delay;
});
topWindow.changeColorScheme(topWindow.colorScheme.name);
makeDraggable(topWindow.cBlock);
// Выравниваем форму по центру, либо по блоку w2g-at-right, если он есть
topWindow.setDefaultPosition = function() {
if (topWindow.setDefaultPositionOnResize) {
if (topWindow.w2gRightBlock != null) {
let bClientRect = topWindow.w2gRightBlock.getBoundingClientRect();
topWindow.cBlock.style.left = (6+bClientRect.left).toString()+'px';
topWindow.cBlock.style.top = (6+bClientRect.top).toString()+'px';
} else {
topWindow.cBlock.style.left = (window.innerWidth/2 - topWindow.cBlock.offsetWidth/2) + 'px';
topWindow.cBlock.style.top = (window.innerHeight/2 - topWindow.cBlock.offsetHeight/2) + 'px';
}
}
}
topWindow.setDefaultPositionOnResize = setDefaultPositionOnResize;
topWindow.setDefaultPosition();
if (topWindow.autoUpdating) {
gameStateUpdater.check();
topWindow.addLogMessage("автообн. запущено");
}
// Создаем нового игрока либо подтягиваем ранее сохраненного
topWindow.player = JSON.parse(localStorage.getItem('posani_quiz_player'));
if (topWindow.player && topWindow.player.nick) {
if (W2GNickInput) W2GNickInput.value = topWindow.player.nick;
topWindow.playerPanel.nickInput.value = topWindow.player.nick;
topWindow.addLogMessage("игрок "+ topWindow.player.nick);
} else {
topWindow.player = {};
topWindow.player.nick = 'player';
topWindow.player.UUID = generateUuidv4();
topWindow.playerPanel.nickInput.value = topWindow.player.nick;
localStorage.setItem('posani_quiz_player', JSON.stringify(topWindow.player));
topWindow.addLogMessage("это ноый игрок");
}
topWindow.addLogMessage("окно инициализировано");
};
// ====================================================================
// ====================== КОНЕЦ initTopWindow ==========================
// Сокрашаем полный адрес ютуб-видео до "yt~XXXXXXXX"
var getShortYTAdress = function(adress) {
let shortAdress = adress;
if (adress.search('youtube')>0) {
shortAdress = "yt~"+adress.split("?v=")[1];
}
return shortAdress;
}
// Подгружаем с сервера свежие данные
var loadTopData = function () {
var tdPath = topWindow.hostAdress + "/curgame"
var XHR = new XMLHttpRequest();
XHR.open('GET', tdPath);
XHR.setRequestHeader('Cache-Control', 'no-cache, no-store, max-age=0');
XHR.onreadystatechange = function() {
if (XHR.readyState === XMLHttpRequest.DONE) {
let rText = XHR.responseText;
rText = JSON.parse(decodeURIComponent(escape(atob(rText))));
topData = rText;
if (!topData.players) {
topWindow.addLogMessage("неверные данные");
return;
}
if (!topData.UUID) topData.UUID = "00000000-0000-0000-0000-000000000000";
updateTopTable();
topWindow.playerPanel.answerBtnSend.disabled = false;
var tNow = getTimeNow();
document.querySelector('#client-top-header-caption').innerHTML = topData.name;
document.querySelector('#client-top-header-caption').title = topData.UUID;
document.querySelector('#client-top-header-game-date').innerHTML = topData.date;
document.querySelector('#client-bottom-panel-update-time').innerHTML = tNow;
document.querySelector('#client-bottom-panel-last-message').innerHTML = 'обновлено успешно';
document.querySelector('#client-bottom-panel-video-adress').innerHTML = getShortYTAdress(topData.videoAdress);
topWindow.playerPanel.nickContainer.style.display = "flex";
topWindow.changeColorScheme(topWindow.colorScheme.name);
if (topData.stopped) {
if (topData.stopped == true) {
topWindow.autoUpdating = false;
topWindow.autoUpdateCheckbox.checked = false;
topWindow.addLogMessage("игра остановлена");
} else topWindow.addLogMessage("игра синхронизирована");
} else topWindow.addLogMessage("игра синхронизирована");
}
};
XHR.onerror = function() {
topWindow.addLogMessage("проблема с сервером");
};
XHR.send();
};
// Отправляем состояние игрока на сервер
function sendPlayerState () {
var psPath = topWindow.hostAdress +"/pRec.php";
var XHR = new XMLHttpRequest();
XHR.open('POST', psPath);
XHR.setRequestHeader('Cache-Control', 'no-cache, no-store, max-age=0');
XHR.onreadystatechange = function() {
if (XHR.readyState === XMLHttpRequest.DONE) {
let rText = XHR.responseText;
var tNow = getTimeNow();
document.querySelector('#client-bottom-panel-update-time').innerHTML = tNow;
if (rText == "SC") {
topWindow.addLogMessage("статус "+topWindow.player.state+" передан");
playerStateUpdater.check();
} else {
topWindow.playerPanel.indicator.style.backgroundColor = "red";
topWindow.playerPanel.indicator.innerHTML = "!";
topWindow.playerPanel.indicator.title = "проблема сервера";
}
}
};
XHR.onerror = function() {
topWindow.playerPanel.indicator.style.backgroundColor = "red";
topWindow.playerPanel.indicator.innerHTML = "!";
topWindow.playerPanel.indicator.title = "Проблема сервера";
topWindow.addLogMessage("проблема с сервером");
};
var sendData = {
type : "psync",
gameUUID : topData.UUID,
player : {
name : topWindow.player.nick,
UUID : topWindow.player.UUID,
state : topWindow.player.state,
answer : topWindow.player.answer
}
}
//console.log(JSON.stringify(sendData));
XHR.send(JSON.stringify(sendData));
topWindow.playerPanel.indicator.style.backgroundColor = "yellow";
topWindow.playerPanel.indicator.innerHTML = "^";
topWindow.playerPanel.indicator.title = "Состояние синхронизируется";
};
// Перестраиваем таблицу топа с актуальной информацией
var updateTopTable = function() {
const sortFn = (a, b) => {
if (a.points < b.points) { return 1;
} else if (a.points > b.points) { return -1; }
return 0;
};
topData.players.sort(sortFn);
topWindow.topBlock.innerHTML = "";
var placeN = 1;
for (let i = 0; i < topData.players.length; i++) {
pString = "  "+placeN + " ";
if (placeN == 1) { pString = "🏆"; }
if (placeN == 2) { pString = "🥈"; }
if (placeN == 3) { pString = "🥉"; }
topWindow.topBlock.innerHTML +=
"
"
+"
"+pString+"
"
+""
+""
+"
";
tpNameElement = document.querySelector("#top"+placeN+"-player-names");
tpScoreElement = document.querySelector("#top"+placeN+"-score");
tpNameElement.innerHTML = topData.players[i].name;
tpScoreElement.innerHTML = topData.players[i].points;
for (let j = i+1; j < topData.players.length; j++) {
if (topData.players[j].points >= topData.players[i].points) {
tpNameElement.innerHTML += " " + topData.players[j].name;
i = i+1;
}
}
placeN += 1;
}
topWindow.changeColorScheme(topWindow.curColorSchemeName);
};
function makeDraggable (element) {
// Make an element draggable (or if it has a .window-top class, drag based on the .window-top element)
let currentPosX = 0, currentPosY = 0, previousPosX = 0, previousPosY = 0;
// If there is a window-top classed element, attach to that element instead of full window
if (element.querySelector('#client-top-header')) {
// If present, the window-top element is where you move the parent element from
element.querySelector('#client-top-header').onmousedown = dragMouseDown;
}
else {
// Otherwise, move the element itself
element.onmousedown = dragMouseDown;
}
function dragMouseDown (e) {
// Prevent any default action on this element (you can remove if you need this element to perform its default action)
e.preventDefault();
// Get the mouse cursor position and set the initial previous positions to begin
previousPosX = e.clientX;
previousPosY = e.clientY;
// When the mouse is let go, call the closing event
document.onmouseup = closeDragElement;
// call a function whenever the cursor moves
document.onmousemove = elementDrag;
}
function elementDrag (e) {
// Prevent any default action on this element (you can remove if you need this element to perform its default action)
e.preventDefault();
// Calculate the new cursor position by using the previous x and y positions of the mouse
currentPosX = previousPosX - e.clientX;
currentPosY = previousPosY - e.clientY;
// Replace the previous positions with the new x and y positions of the mouse
previousPosX = e.clientX;
previousPosY = e.clientY;
// Set the element's new position
element.style.top = (element.offsetTop - currentPosY) + 'px';
element.style.left = (element.offsetLeft - currentPosX) + 'px';
}
function closeDragElement () {
// Stop moving when mouse button is released and release events
document.onmouseup = null;
document.onmousemove = null;
}
}
var W2GNickInput = document.querySelector("#nickname-form-nickname");
topWindow.hostAdress = defaultHostAdress;
window.addEventListener("load", ()=>{
// Запускаем ету шарманку
initTopWindow();
});
// Выравниваем форму по центру при ресайзе окна браузера
window.addEventListener('resize', () => {
topWindow.setDefaultPosition()
});
if (W2GNickInput) W2GNickInput.addEventListener('change', () => {
topWindow.playerPanel.nickInput.value = W2GNickInput.value;
setPlayerNick(W2GNickInput.value);
});