Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* ON.LOAD */
- "use strict";
- var div_array = ["menu", "tableRankingDiv", "menu_jogo", "gameDiv", "sidebar", "sb_option", "ajuda1", "replay", "option1", "option1_1", "option1_2", "start_1", "start_2"];
- window.onload = function() {
- document.getElementById("login").style.display = "block";
- for(var i=0; i < div_array.length; i++){
- document.getElementById(div_array[i]).style.display = "none";
- }
- };
- /* ------- */
- /* Variaveis */
- var username;
- var password;
- var game;
- var evtSource;
- var timeOutMessage;
- var timer;
- var timeLeft;
- var active_player = 0;
- var game_active = false;
- var player_color = Array();
- var loginflag = false;
- player_color[1] = "red";
- player_color[2] = "blue";
- var player_w = 0;
- var player_l = 0;
- var boardSize;
- var ongame = 0;
- /* ---------- */
- /* Server url */
- var url = "http://twserver.alunos.dcc.fc.up.pt:8008/";
- /* JOGO */
- function Board(k) {
- this.k = k;
- this.tabuleiro = new Array();
- this.boardDiv;
- this.createBoard = function() {
- this.boardDiv = document.createElement("div");
- this.boardDiv.className = "boardDiv";
- this.boardDiv.id = "boardDiv";
- this.boardDiv.style.width = "" + (75 * (this.k)) + "px";
- this.boardDiv.style.height = "" + (75 * (this.k)) + "px";
- document.getElementById("gameDiv").appendChild(this.boardDiv);
- for(let i=0; i<this.k; i++){
- this.tabuleiro[i] = new Array();
- var coluna = document.createElement("div");
- coluna.className = "coluna";
- coluna.id = "col_" + i;
- coluna.title = i;
- document.getElementById("boardDiv").appendChild(coluna);
- for(var j=0; j<this.k; j++){
- this.tabuleiro[i].push(0);
- var celula = new Cell(i, j);
- document.getElementById("col_" + i).appendChild(celula.html)
- }
- coluna.onclick = function() {
- if(game_active){
- if(ongame == 0){
- for(let j = (game.board.k-1) ; j>=0; j--){
- let cell = document.getElementById("piece_" + i + "_" + j);
- if(game.board.tabuleiro[i][j]==0){
- game.board.tabuleiro[i][j] = active_player;
- cell.src = "img/" + player_color[active_player] + "_piece.png";
- if(game.n_players == 2){
- if (active_player == 1) { active_player = 2; }
- else { active_player = 1; }
- game.checkForWin();
- }
- else if(game.n_players == 1){
- if (active_player == 1) {
- active_player = 2;
- if(game_active){
- game.pc.move();
- game.checkForWin();
- }
- }
- else { active_player = 1; }
- }
- game.setUpTurn();
- return;
- }
- }
- }
- else{
- if(active_player != username)
- document.getElementById("messageH1").innerHTML = "Não é a sua vez de jogar.";
- else{
- game.notify(Number(this.title));
- for(let j = (game.board.k-1) ; j>=0; j--){
- let cell = document.getElementById("piece_" + i + "_" + j);
- if(game.board.tabuleiro[i][j]==0){
- game.board.tabuleiro[i][j] = active_player;
- if(active_player == username){
- cell.src = "img/red_piece.png";
- }
- else if(active_player != 0){
- cell.src = "img/blue_piece.png";
- }
- return;
- }
- }
- }
- }
- }
- }
- }
- }
- }
- function newGame(boardSize, f_player, n_players) {
- game_active = true;
- active_player = f_player;
- game = new Game(boardSize, f_player, n_players);
- game.initiateGame();
- game.setUpTurn();
- }
- function Game(boardSize, f_player, n_players) {
- this.firstPlayer = f_player;
- this.boardSize = boardSize;
- this.n_players=n_players;
- this.game_active;
- this.pc = new PC(1);
- this.board;
- this.moves;
- var xhr = new XMLHttpRequest();
- this.initiateGame = function() {
- this.board = new Board(this.boardSize);
- this.active_player = this.firstPlayer;
- this.moves = 0;
- this.game_active = true;
- resetGameDiv();
- var messageH = document.createElement("h1");
- messageH.id = "messageDiv";
- document.getElementById("gameDiv").appendChild(messageH);
- this.board.createBoard();
- show("gameDiv");
- this.setUpTurn();
- }
- this.checkForWin = function() {
- //check left-to-right
- for (var i=1; i<=2; i++) {
- for (var col = 0; col <=3; col++) {
- for (var row = 0; row <boardSize; row++) {
- if (game.board.tabuleiro[row][col] == i) {
- if ((game.board.tabuleiro[row][col+1] == i) && (game.board.tabuleiro[row][col+2] == i) && (game.board.tabuleiro[row][col+3] == i)) {
- game.endGame(i);
- return true;
- }
- }
- }
- }
- }
- //check top-to-bottom
- for (var i=1; i<=2; i++) {
- for (var col = 0; col <boardSize; col++) {
- for (var row = 0; row <=3; row++) {
- if (game.board.tabuleiro[row][col] == i) {
- if ((game.board.tabuleiro[row+1][col] == i) && (game.board.tabuleiro[row+2][col] == i) && (game.board.tabuleiro[row+3][col] == i)) {
- game.endGame(i);
- return true;
- }
- }
- }
- }
- }
- //check diagnol down
- for (var i=1; i<=2; i++) {
- for (var col = 0; col <boardSize-3; col++) {
- for (var row = 0; row <boardSize-3; row++) {
- if (game.board.tabuleiro[row][col] == i) {
- if ((game.board.tabuleiro[row+1][col+1] == i) && (game.board.tabuleiro[row+2][col+2] == i) && (game.board.tabuleiro[row+3][col+3] == i)) {
- game.endGame(i);
- return true;
- }
- }
- }
- }
- }
- //check diagnol up
- for (var i=1; i<=2; i++) {
- for (var col = 0; col <boardSize-3; col++) {
- for (var row = 3; row <boardSize; row++) {
- if (game.board.tabuleiro[row][col] == i) {
- if ((game.board.tabuleiro[row-1][col+1] == i) && (game.board.tabuleiro[row-2][col+2] == i) && (game.board.tabuleiro[row-3][col+3] == i)) {
- game.endGame(i);
- return true;
- }
- }
- }
- }
- }
- }
- this.endGame = function(winner) {
- this.game_active = false;
- document.getElementById("messageDiv").innerHTML = "Vencedor: <span style='color:" + player_color[winner] + "'>Jogador " + winner + "</span>";
- clear("boardDiv");
- show("replay");
- if(winner==1){
- player_w++;
- }
- else if(winner==2){
- player_l++;
- }
- }
- this.setUpTurn = function() {
- if(this.game_active)
- document.getElementById("messageDiv").innerHTML="-> <span style='color:" + player_color[this.active_player] + "'>Player " + active_player + "</span> <-"
- }
- }
- function PC(dif) {
- this.dif=dif;
- this.move = function() {
- var min=100;
- var col_play=0;
- var count=0;
- for(var i=0; i < game.board.tabuleiro.length; i++){
- count=0;
- for(var j=game.board.tabuleiro.length - 1; j >= 0; j--){
- if(game.board.tabuleiro[i][j]!=0)
- count++;
- }
- if(count<min){
- min=count;
- col_play=i;
- }
- }
- document.getElementById("col_" + col_play).click();
- }
- }
- function resetGameDiv(){
- var elem = document.getElementById("gameDiv");
- while (elem.firstChild)
- elem.removeChild(elem.firstChild);
- document.getElementById("gameDiv").style.display="none";
- }
- function Cell(x, y) {
- this.x = x;
- this.y = y;
- this.html = document.createElement("img");
- this.html.className = "piece";
- this.html.id = "piece_" + x + "_" + y;
- this.html.src = "img/void_piece.png";
- this.html.onmouseover = function() {
- if(ongame == 0)
- if(game.board.tabuleiro[x][y]==0){
- document.getElementById("piece_" + x + "_" + y).src = "img/" + player_color[active_player] + "_piece.png";
- }
- else{
- if(active_player == username)
- document.getElementById("piece_" + x + "_" + y).src = "img/red_piece.png";
- else
- document.getElementById("piece_" + x + "_" + y).src = "img/blue_piece.png";
- }
- }
- this.html.onmouseleave = function() {
- if(game.board.tabuleiro[x][y]==0){
- document.getElementById("piece_" + x + "_" + y).src = "img/void_piece.png";
- }
- }
- }
- /* FIM JOGO */
- /* OPÇÕES */
- function logged() {
- show("menu");
- clear("login");
- }
- function clear_show(k) {
- if(document.getElementById(k).style.display === "none") {
- document.getElementById(k).style.display = "block";
- }
- else if(document.getElementById(k).style.display === "block"){
- document.getElementById(k).style.display = "none";
- }
- }
- function clear(k) {
- document.getElementById(k).style.display = "none";
- }
- function show(k) {
- document.getElementById(k).style.display = "block";
- }
- function restartGame() {
- clear("replay");
- resetGameDiv();
- clear("sidebar");
- clear("sb_option");
- show("menu_jogo");
- }
- function leaveGame() {
- clear("replay");
- resetGameDiv();
- clear("sidebar");
- clear("sb_option");
- logged();
- }
- function jogar() {
- clear("menu");
- show("menu_jogo");
- show("option1");
- clear("option1_1");
- clear("option1_2");
- clear("start_1");
- clear("start_2");
- }
- function jogo(k, fst_player, n) {
- clear("menu_jogo");
- document.getElementById("record").innerHTML="Vitórias: " + player_w + "<br>Derrotas: " + player_l + "<br>";
- show("sb_option");
- clear("menu");
- newGame(k, fst_player, n);
- }
- function sairjogo() {
- if(active_player==1){
- document.getElementById("messageDiv").innerHTML = "Vencedor: <span style='color:" + player_color[2] + "'>Jogador 2</span>";
- player_l++;
- }
- else if(active_player==2){
- document.getElementById("messageDiv").innerHTML = "Vencedor: <span style='color:" + player_color[1] + "'>Jogador 1</span>";
- player_w++;
- }
- show("replay");
- game.game_active=false;
- clear("boardDiv");
- }
- function sidebar() {
- clear_show("sidebar");
- }
- function sb_instructions() {
- clear_show("ajuda1");
- clear_show("gameDiv");
- }
- function option1(k) {
- if(k=="2"){ show("option1_1"); }
- else{ show("option1_2"); }
- clear("option1");
- }
- function option1_1(k) {
- if(k==2){
- show("start_1");
- }
- else{
- show("start_2");
- }
- clear("option1_1");
- }
- function option1_2(k) {}
- function online() {}
- function logout() {
- location.reload();
- }
- /* FIM OPÇÕES */
- /* SERVER COMMANDS */
- function register(){
- username = document.getElementById("user").value;
- password = document.getElementById("psw").value;
- var js_obj = {"nick": username, "pass": password};
- var json = JSON.stringify(js_obj);
- var xhr = new XMLHttpRequest();
- xhr.open("POST", url+"register", true);
- xhr.send(json);
- xhr.onreadystatechange = function() {
- if(this.readyState != 4)
- return;
- else if(this.status == 200){
- document.getElementById("showLoginDiv").style.display = "block";
- document.getElementById("showLoginText").innerHTML = "Welcome, " + username + "!";
- loginflag=true;
- if(localStorage[username] == null)
- localStorage[username] = JSON.stringify({"victories": 0, "games": 0});
- logged();
- }
- else if(this.status == 400){
- var login_error = document.createElement("p");
- login_error.id = "badLogin";
- document.getElementById("login").appendChild(login_error);
- document.getElementById("badLogin").innerHTML = JSON.parse(this.responseText).error;
- }
- }
- }
- function join(size){
- boardSize = size;
- resetGameDiv();
- var messageH = document.createElement("h1");
- messageH.id = "messageH1";
- document.getElementById("gameDiv").appendChild(messageH);
- var timerH = document.createElement("h2");
- timerH.id = "timerH2";
- document.getElementById("gameDiv").appendChild(timerH);
- setTimer();
- show("gameDiv");
- var js_obj = {"grupo": 42, "nick": username, "pass": password, "size": { "rows": Number(boardSize), "columns": Number(boardSize) } };
- var jSon = JSON.stringify(js_obj);
- var xhr = new XMLHttpRequest();
- xhr.open("POST", url+"join", true);
- xhr.send(jSon);
- xhr.onreadystatechange = function() {
- if(this.readyState != 4)
- return;
- else if(this.status == 200){
- var gameId = JSON.parse(this.responseText)["game"];
- initiateEventSource(gameId);
- messageH.innerHTML = "À espera de jogador...";
- document.getElementById("option1_2").style.display = "none";
- }
- else if(this.status == 400){
- var json = JSON.parse(this.responseText);
- if(json["error"]=="Invalid size")
- messageH.innerHTML = "Erro! Tamanho incorreto.";
- else
- messageH.innerHTML = "Erro na ligação! Volte a tentar.";
- }
- else if(this.status >= 500)
- messageH.innerHTML = "Erro! Má conexão ao servidor.";
- var back = document.createElement("BUTTON");
- back.id = "returnbutton";
- back.type = "button";
- back.value = "Voltar";
- back.onclick = function(){
- game_active = false;
- gameId = null;
- document.getElementById("gameDiv").removeChild(back);
- document.getElementById("menu_jogo").style.display = "none";
- messageH.innerHTML = "";
- logged();
- }
- document.getElementById("gameDiv").appendChild(back);
- }
- }
- // ONLINE GAME //
- function OnlineGame(gameId, boardSize, firstPlayer){
- this.gameId = gameId;
- this.boardSize = boardSize;
- active_player = firstPlayer;
- this.turn;
- this.board;
- ongame = 1;
- this.initiateGame = function(firstPlayer){
- this.board = new Board(this.boardSize, this.boardSize);
- this.board.createBoard();
- this.turn = firstPlayer;
- this.updateMessageDiv();
- }
- this.updateMessageDiv = function(){
- clearTimeout(timeOutMessage);
- document.getElementById("messageH1").innerHTML = "-> Vez de " + active_player + " jogar <-";
- }
- this.notify = function(c){
- var xhr = new XMLHttpRequest();
- xhr.open("POST", url+"notify", true);
- xhr.send(JSON.stringify({"nick": username, "pass": password, "game": this.gameId, "column": Number(c)}));
- xhr.onreadystatechange = function() {
- if(this.readyState != 4)
- return;
- else if(this.status == 400){
- var json = JSON.parse(this.responseText);
- if(json["error"] == "Not your turn to play"){
- document.getElementById("messageH1").innerHTML = "Não é a sua vez!";
- timeOutMessage = setTimeout("game.updateMessageDiv()", 3000);
- }
- else{
- document.getElementById("messageH1").innerHTML = "Jogada inválida!";
- timeOutMessage = setTimeout("game.updateMessageDiv()", 3000);
- }
- }
- }
- }
- this.move = function(i){
- console.log("move");
- if(game_active){
- for(let j = (game.board.k-1); j>=0; j--){
- let cell = document.getElementById("piece_" + i + "_" + j);
- if(game.board.tabuleiro[i][j]==0){
- game.board.tabuleiro[i][j] = active_player;
- cell.src = "img/blue_piece.png";
- console.log(game.board.tabuleiro[i][j]);
- return;
- }
- }
- }
- }
- this.setUpTurn = function(){
- console.log("setupturn");
- if(game_active)
- document.getElementById("messageDiv").innerHTML="-> Player " + active_player + " <-";
- game.updateMessageDiv();
- }
- this.endGame = function(winner){
- clearTimeout(timeOutMessage);
- if(winner == username)
- document.getElementById("messageH1").innerHTML = " Parabéns! Ganhou!!! ";
- else
- document.getElementById("messageH1").innerHTML = " Perdeu. ";
- game_active = false;
- document.getElementById("boardDiv").style.display = "none";
- document.getElementById("timerH2").style.display = "none";
- clearInterval(timer);
- evtSource.close();
- }
- this.leave = function(){
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function() {
- if(this.readyState != 4)
- return;
- else if(this.status == 400){
- clearTimeout(timeOutMessage);
- document.getElementById("messageH1").innerHTML = "Error! Bad request.";
- }
- }
- xhr.open("POST", url+"leave", true);
- xhr.send(JSON.stringify({"nick": username, "pass": password, "game": this.gameId}));
- clearInterval(timer);
- }
- }
- function initiateEventSource(gameId){
- evtSource = new EventSource(url + "update?nick=" + username + "&game=" + gameId);
- evtSource.onmessage = function(packet){
- var json = JSON.parse(packet.data);
- if(json["turn"]!=null){
- if(game_active){
- active_player = json["turn"];
- game.updateMessageDiv();
- if(active_player==username) {
- setTimer();var x = json["column"];
- var x = json["column"];
- game.move(Number(x));
- }
- else{
- clearInterval(timer);
- document.getElementById("timerH2").innerHTML = "1m 0s"
- }
- }
- else{
- game_active = true;
- active_player = json["turn"];
- game = new OnlineGame(gameId, boardSize, active_player);
- game.initiateGame(json["turn"]);
- if(active_player==username) {
- setTimer();
- var x = json["column"];
- game.move(Number(x));
- }
- else{
- clearInterval(timer);
- document.getElementById("timerH2").innerHTML = "1m 0s"
- }
- }
- }
- else if(json["winner"]!=null){
- game.endGame(json["winner"]);
- }
- else if(json["error"]){
- if(json["error"]=="Invalid game reference"){
- clearTimeout(timeOutMessage);
- document.getElementById("messageH1").innerHTML = "Erro! Game ID incorreto.";
- }
- else{
- clearTimeout(timeOutMessage);
- document.getElementById("messageH1").innerHTML = json["error"];
- }
- }
- else if(json["winner"]==null){
- if(timeLeft<=0){
- setTimeout(function(){
- game_active = false;
- evtSource.close();
- }
- ,3000);
- }
- else{
- game_active = false;
- evtSource.close();
- }
- }
- }
- }
- function showMultiplayerRanks(boardSize){
- var xhr = new XMLHttpRequest();
- show("tableRankingDiv");
- clear("menu");
- xhr.onreadystatechange = function() {
- if(this.readyState != 4)
- return;
- if(this.status == 200){
- var json = JSON.parse(this.responseText).ranking;
- var finalText =
- "<div class='rankings'>" +
- "<table>" +
- "<tr>" +
- "<th>Player</th>" +
- "<th>Total of games</th>" +
- "<th>Victories</th>" +
- "<th>Loses</th>" +
- "<th>Victories/Loses Ratio</th>" +
- "</tr>";
- if(json != null){
- for(var j=0; j<json.length; j++){
- finalText +=
- "<tr>" +
- "<td>" + json[j].nick + "</td>" +
- "<td>" + json[j].games + "</td>" +
- "<td>" + json[j].victories + "</td>" +
- "<td>" + (json[j].games - json[j].victories) + "</td>" +
- "<td>" + ((json[j].victories / json[j].games)*100).toFixed(2) + "%" + "</td>";
- finalText += "</tr>";
- }
- }
- finalText +=
- "</table>"
- "</div>";
- var btn = "<button type='button' onclick='leaveRankings()'>Voltar</button>";
- finalText += btn;
- document.getElementById("tableRankingDiv").innerHTML = finalText;
- }
- else if(this.status == 400){
- var json = JSON.parse(this.responseText);
- document.getElementById("tableRankingDiv").innerHTML = json.error;
- }
- }
- xhr.open("POST", url+"ranking", true);
- xhr.send(JSON.stringify({"size": {"rows": boardSize, "columns": boardSize}}));
- }
- function leaveRankings(){
- clear("tableRankingDiv");
- show("menu");
- }
- function setTimer(){
- timeLeft = 60000;
- clearInterval(timer);
- timer = setInterval(function() {
- // Time calculations for days, hours, minutes and seconds
- var minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
- var seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
- // Display the result in the element with id="demo"
- document.getElementById("timerH2").innerHTML = minutes + "m " + seconds + "s ";
- // If the count down is finished, write some text
- if (timeLeft <= 0) {
- clearInterval(timer);
- if(singleORmulti == "single")
- document.getElementById("timerH2").innerHTML = "Time to play exceeded!";
- else
- document.getElementById("timerH2").innerHTML = "Time to find an opponent exceeded!";
- document.getElementById("leaveGameDiv").style.display = "none";
- if(document.getElementById("boardDiv")!=null)
- document.getElementById("boardDiv").style.display = "none";
- gameInProgress = false;
- leaveGame();
- }
- timeLeft=timeLeft-1000;
- }, 1000);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement