瀏覽代碼

iHanoi is now usable directly from browser without needing iTarefa on moodle

Bernardo Martins 5 年之前
父節點
當前提交
0caaaab82e
共有 4 個文件被更改,包括 49 次插入144 次删除
  1. 29 10
      iHanoi.html
  2. 15 14
      js/iHanoiFunctions.js
  3. 0 117
      js/integration-functions.js
  4. 5 3
      js/start.js

+ 29 - 10
iHanoi.html

@@ -4,9 +4,18 @@
 	<head>
 		<title> Torre de Hanoi </title>
 		<Style>
+			#Disk_quantity{
+				position: absolute;
+				height: 10%;
+				width: 5%;
+				top: 5%;
+				right: 3%;
+				font-size: 200%;
+				text-align-last:center;
+			}
 			#planoDeFundo {
-				background :transparent;
-				width: 90%; 
+				background :#d7f3f9;
+				width: 90%;
 				height: 75%;
 				position: absolute;
 			}
@@ -73,26 +82,36 @@
 				left: 51%;
 				top: 83%;
 			}
+			#Restart_button{
+				position:absolute;
+				border:1px solid gray;
+				border-radius: 7%;
+				font-size: 1;
+				height: 5%;
+				word-wrap: break-word;
+				width: 20%;
+				left: 35.5%;
+				top: 89%;
+			}
 		</Style>
 		<script src="js/jquery-3.3.1.min.js"></script>
-		<script src="js/integration-functions.js"></script>
 	</head>
 	<body>
-	<div class="task"  style="display:none">
+	<div class="task" >
 		<button id="A_button" onclick="buttonClick(0)">A</button>
 		<button id="B_button" onclick="buttonClick(1)">B</button>
 		<button id="C_button" onclick="buttonClick(2)">C</button>
-		<button id="Undo_button" onclick="undo()">Undo</button>
-		<button id="Redo_button" onclick="redo()">Redo</button>
+		<button id="Undo_button" onclick="undo()">Desfazer</button>
+		<button id="Redo_button" onclick="redo()">Refazer</button>
+		<button id="Restart_button" onclick="reset(nDisks)">Recomeçar</button>
 		<canvas id="planoDeFundo"  width="1024" height="615">
 		Seu navegador não suporta o recurso Canvas. Atualize-o para utilizar esse recurso
 		</canvas>
 		<script src= "js/start.js"></script>
 		<script src="js/iHanoiFunctions.js"></script>
 	</div>
-	<div class="creation" style="display:none">
-		Quantidade de discos no desafio: 
-		<select name="Discos" class="cDiscos">
+	<div class="creation">
+		<select id="Disk_quantity" name="Discos" class="cDiscos" onChange="reset(this.value)">
 			<option>2</option>
 			<option>3</option>
 			<option>4</option>
@@ -101,4 +120,4 @@
 		</select>
 	</div>
   </body>
-</html>
+</html>

+ 15 - 14
js/iHanoiFunctions.js

@@ -33,7 +33,8 @@ class Disk{
 		context.clearRect(this.x, this.y, this.w, this.h);
 	}
 }
-function reinicio (){
+function reset (QntityDisks){
+	nDisks = QntityDisks;
 	towerA.splice(0,towerA.length);
 	towerB.splice(0,towerB.length);
 	towerC.splice(0,towerC.length);
@@ -42,7 +43,7 @@ function reinicio (){
 	idF = " ";
 	idT=" ";
 	toMove=null;
-	inicio(nDisks);
+	inicio(QntityDisks);
 }
 function drawTowers (){
 	context.beginPath();
@@ -113,8 +114,8 @@ function getTower (id){
 function drawFromTo (){
 	context.font = "50px Arial";
 	context.fillStyle = "black";
-	context.fillText("Move from "+idF+" to "+idT, 50, 50);
-	context.fillText("Movements: "+nTotalMovements, 50, 100);
+	context.fillText("Mover de "+idF+" para "+idT, 50, 50);
+	context.fillText("Movimentos: "+nTotalMovements, 50, 100);
 }
 
 
@@ -126,17 +127,17 @@ function moveDisk (origin, destiny){
 		moves.splice(nMovements, moves.length- nMovements);
 	}
 	moves.push(origin+"  "+destiny);
-	
-	//console.log(moves);
+
+
 	nMovements++;
 	finishMove(origin, destiny);
 	if(towerC.length == nDisks && nDisks!=0){
 		acertou=1;
 		totalTime= Date.now() - start;
 		if(nTotalMovements==optimalSolution){
-			alert("You Won in the least amount of movements!!!\nCongratulations!!!");
+			alert("Você ganhou com a quantidade ótima de movimentos "+optimalSolution+"!!!\nParabens!!!");
 		}else{
-			alert("You Won!!!\nCongratulations!!");
+			alert("Você ganhou com "+nTotalMovements+" movimentos sendo o minimo possível "+optimalSolution);
 		}
 	}
 }
@@ -164,7 +165,7 @@ function roundRect(ctx, x, y, width, height, radius, fill, stroke) {
   }
   if (fill) {
     ctx.fill();
-  }        
+  }
 }
 
 function undo(){
@@ -176,8 +177,8 @@ function undo(){
 			idf = res2[0];
 			idt = res2[1];
 		} else{
-			idf = "";
-			idt = "";
+			idf = "  ";
+			idt = "  ";
 		}
 		finishMove(parseInt(res[1]), parseInt(res[0]));
 	}
@@ -209,13 +210,13 @@ function finishMove(origin, destiny){
 			alert("Movimento Inválido");
 			idF =" ";
 			idT =" ";
-			drawScene();						
+			drawScene();
 		}
-	}else{	
+	}else{
 		topDiskOrigin.x += 345*(destiny-origin);
 		topDiskOrigin.y += 42*(originTower.length-destinyTower.length-1);
 		originTower.pop();
 		destinyTower.push(topDiskOrigin);
 		drawScene();
 	}
-}
+}

+ 0 - 117
js/integration-functions.js

@@ -1,117 +0,0 @@
-// Função para ler parâmetros informados pelo iTarefa via URL
-// Apesar de não ser obrigatório, será muito útil para capturar os parâmetros
-function getParameterByName(name) {
-    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
-    return match ? decodeURIComponent(match[1].replace(/\+/g, ' ')) : null;
-}
-
-// Criando um array com os parâmetros informados pelo iTarefa
-// Observe que para cada parâmetro, é realizada a chamada do método getParameterByName, implementado acima
-var iLMparameters = {
-    iLM_PARAM_ServerToGetAnswerURL: getParameterByName("iLM_PARAM_ServerToGetAnswerURL"),
-    iLM_PARAM_SendAnswer: getParameterByName("iLM_PARAM_SendAnswer"),
-    iLM_PARAM_AssignmentURL: getParameterByName("iLM_PARAM_AssignmentURL"),
-    iLM_PARAM_Assignment: getParameterByName("iLM_PARAM_Assignment"),
-    lang: getParameterByName("lang")
-};
-
-// Função chamada pelo iTarefa quando o professor finaliza a criação da atividade
-// ou quando o aluno finaliza a resolução do exercício
-// O retorno é um JSON com os dados do exercício ou da resolução
-// Esse retorno será armazenado no banco de dados do Moodle, pelo iTarefa
-function getAnswer() {
-    // Se o parâmetro "iLM_PARAM_SendAnswer" for false,
-    // então trata-se de resolução de atividade
-    if (iLMparameters.iLM_PARAM_SendAnswer == 'false') {
-        // Montar o retorno da resposta do aluno
-        var teacherReturn ="Numero de discos: "+nDisks+"  Quantidade de Movimentos: "+nTotalMovements+
-                            "\nQuantidade de erros: "+nWrongMoves+"  Tempo Total: "+totalTime+
-                            "\n --De Para";
-        for(var i=0; i<totalMoves.length; i++){
-            teacherReturn+="\n"+totalMoves[i];
-        }
-        return teacherReturn;
-    } else {//se for o professor acessando, mostra a pagina de elaboração
-        return "Número de Discos: "+$('.cDiscos').val();
-    }
-}
-
-// Função chamada pelo iTarefa para receber a nota do aluno na atividade
-// O retorno é um valor entre 0.0 e 1.0
-function getEvaluation() {
-    if (iLMparameters.iLM_PARAM_SendAnswer == 'false') {
-        // Calcula a nota do aluno:
-
-
-        // Agora, verificamos se o aluno acertou
-       // var acertos = 0;
-        
-        // Cálculo da nota: resposta correta =1, errada =0
-        var nota = acertou;
-
-        // A chamada do método abaixo é obrigatória!
-        // Observe que a chamada parte do iLM para o iTarefa
-        parent.getEvaluationCallback(nota);
-    }
-}
-
-
-// Função para que o iMA leia os dados da atividade fornecidos pelo iTarefa
-function getiLMContent() {
-
-    // O parâmetro "iLM_PARAM_Assignment" fornece o URL do endereço que deve ser
-    // requisitado via AJAX para a captura dos dados da atividade
-    $.get(iLMparameters.iLM_PARAM_Assignment, function (d) {
-        // Uma vez que os dados foram recebidos, o método "organizaAtividade" é chamado.
-        // Observe que esse método faz parte do arquivo js/iarithmetic-functions.js
-        console.log(d);
-        res = d.split(" ");
-        loadIMGS(parseInt(res[3]));
-        if (res.indexOf("Quantidade")!=-1){
-            document.getElementById("A_button").disabled = true;
-            document.getElementById("B_button").disabled = true;
-            document.getElementById("C_button").disabled = true;
-            res = d.split("\n");
-            var j = 0
-            while(res[j].indexOf("--")==-1){
-                j++;
-            }
-            j++;
-            while(j<res.length){
-                res2 = res[j].split("  ");
-                nTotalMovements--;
-                console.log(res2);
-                idF= res2[0];
-                idT= res2[1];
-                finishMove(parseInt(res2[0]),parseInt(res2[1]));
-                j++;
-            }
-        }
-    });
-}
-
-// Adicionamos a diretiva .ready(), para que quando a página HTML estiver carregada,
-// seja verificado qual a visualização deve ser apresentada: se a área de construção
-// de atividade ou de resolução. E no caso de ser resolução, os dados da atividade
-// precisam ser consultados, pelo método implementado acima, o getiLMContent()
-$(document).ready(function() {
-    // Se iLM_PARAM_SendAnswer for false, então trata-se de resolução de atividade,
-    // portanto, a "DIV" de resolução é liberada
-    if (iLMparameters.iLM_PARAM_SendAnswer == 'false') {
-        $('.task').css("display","block");
-        getiLMContent();
-    } else {
-        // Caso não esteja em modo de resolução de atividade, a visualização no momento
-        // é para a elaboração de atividade:
-        $('.creation').css("display","block");
-    }
-});
-
-function sleep(milliseconds) {
-  var startSleep = new Date().getTime();
-  for (var i = 0; i < 1e7; i++) {
-    if ((new Date().getTime() - startSleep) > milliseconds){
-      break;
-    }
-  }
-}

+ 5 - 3
js/start.js

@@ -3,7 +3,7 @@ var context = canvas.getContext('2d');
 var towerA = [], towerB = [], towerC = [];
 var toMove = null;
 var idF=" ", idT= " ";
-var nMovements = 0, nTotalMovements = 0, nWrongMoves = 0, nDisks;
+var nMovements = 0, nTotalMovements = 0, nWrongMoves = 0, nDisks = 2;
 var moves = [], totalMoves = []; //vector to save movements
 var acertou=0;
 var optimalSolution;
@@ -12,11 +12,13 @@ var colors = ["#000080","#00FF00", "#FF00FF", "yellow", "#FFA500", "#B0C4DE","re
 var start = Date.now(), startOfMove, totalTime, moveTime; //timing vars
 var pat;
 
-function loadIMGS(n){
+loadIMGS(nDisks);
+
+function loadIMGS (n){
 	var img = new Image();
 	img.onload = function(){
 		pat = context.createPattern(img, "repeat");
 		inicio(n);
 	};
 	img.src = 'imgs/wood1.jpeg';
-}
+}