JavaScript - Número del Soroban

 
Vista:
sin imagen de perfil

Número del Soroban

Publicado por Axel (2 intervenciones) el 31/05/2023 17:57:01
Buenas tardes, soy muy nuevo en esto de programar y solo lo hago en los ratos libres, ya que mi trabajo es otro (profesor) y programo (si se puede llamar así) solo para crear algunas pequeñas aplicaciones y juegos para mis alumnos. Casi siempre lo que hago es modificar código de gente que lo comparte gratuitamente.

Os cuento, quiero crear un soroban para que mis alumnos puedan practicar online, para ello he hecho uso del que nos dejan aquí: https://mmurak.github.io/SorobanTrainer/index.html. He modificado el código para que solo se vea una barra y que no haya manuales ni nada parecido, quiero que los alumnos aprendan a usar el soroban solo con las unidades (de momento).

Todo funciona perfectamente, el problema es cuando he intentado que también se muestre el número que muestra el soroban en forma decimal, he probado muchas cosas y nada funciona. Seguramente sea algo simplísimo para los que saben programar de verdad. Pero yo no he sido capaz, lo único que sé es que seguramente el número decimal se pueda sacar de la función interna: interpret(num) , pero como he dicho yo no he sido capaz. Os dejo el código simplificado para ver si alguien me da una pista:

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
let resourcedir = "./soroban/";
let imgfilename0 = "soroban0.gif";
let imgfilename1 = "soroban1.gif";
let imgfilenameU = "sorobanU.gif";
let imgfilenameL = "sorobanL.gif";
let imgfilenameB0 = "soroband0.gif";
let imgfilenameB1 = "soroband1.gif";
let digitsoroban;
let heavenBeads;
let earthBeads;
let digitclusters;
let unitsLabel = "百拾里拾町拾間尺寸分 百拾万阡百拾壱分厘";
 
let shiftkey = false;
 
let undoBuffer = [];
let redoBuffer = [];
 
let initialPatternBuffer = [];
let exitPatternBuffer = [];
let tutorialBuffer = [];
let pagePointer = 0;
 
let bucket = [];
let soundFlag = true;
 
//
 
 
//
// Bead movement
//
function mv(name) {
  let hore = name.substring(0, 2);
  let indexY = name.substring(2, 4);
  let indexX = name.substring(4);
  let img = document.images[name].src;
  if (img.indexOf(imgfilename0) < 0) {  // if rod then nop
    undoBuffer.push(encodeAbacus());
    document.getElementById("UNDO").disabled=false;
    redoBuffer = [];
    document.getElementById("REDO").disabled=true;
    playsound();
    if (hore == 'hb') {  // heaven bead
      for (i = 0; i <= heavenBeads; i++) {
        putimg(hore + indexY + i, imgfilename1);
      }
      if ((heavenBeads > 1) && shiftkey && indexX <= 1) {
        putimg(hore + indexY + 0, imgfilenameU);
        putimg(hore + indexY + 1, imgfilenameL);
      } else {
        putimg(name, imgfilename0);
      }
    } else {  // earth beads
      for (i = 0; i <= earthBeads; i++) {
        putimg(hore + indexY + i, imgfilename1);
      }
      putimg(name, imgfilename0);
    }
  }
  document.getElementById("cuenta-movida").innerText = name;
}
 
function putimg(objname, filename) {
  if (document.images[objname].src.indexOf(filename) < 0) {
    document.images[objname].src = resourcedir + filename;
  }
  }
 
//
// Reset field, and undo/redo buffers
//
function resetsoroban() {
  setsoroban('', '');
  undoBuffer = [];
  redoBuffer= [];
  document.getElementById("UNDO").disabled=true;
  document.getElementById("REDO").disabled=true;
  playsoundClear();
}
 
//
// Set patterns from internal-rep. (/[uVWX]+:[0-5]+/)
//
function setsoroban(heavens, earths) {
  playsound();
  let hvn = heavens.replace(/ +/g, '');
  hvn = hvn + 'u'.repeat(digitsoroban);  // benevolent process
  hvn = hvn.split('');
  let erth = earths.replace(/ +/g, '');
  erth = erth + '0'.repeat(digitsoroban);  // benevolent process
  erth = erth.split('');
  for (i = 0; i < digitsoroban; i++) {
    common = 'hb' +  ("00" +  i).slice(-2);
    switch (hvn.shift().toUpperCase()) {
      case 'X' :
        putimg(common + '0', imgfilenameU);
        putimg(common + '1', imgfilenameL);
        putimg(common + '2', imgfilename1);
        break;
      case 'W' :
        putimg(common + '0', imgfilename0);
        putimg(common + '1', imgfilename1);
        putimg(common + '2', imgfilename1);
        break;
      case 'V' :
        if (heavenBeads == 2) {
          putimg(common + '0', imgfilename1);
          putimg(common + '1', imgfilename0);
          putimg(common + '2', imgfilename1);
        } else {
          putimg(common + '0', imgfilename0);
          putimg(common + '1', imgfilename1);
        }
        break;
      default :
        if (heavenBeads == 2) {
          putimg(common + '0', imgfilename1);
          putimg(common + '1', imgfilename1);
          putimg(common + '2', imgfilename0);
        } else {
          putimg(common + '0', imgfilename1);
          putimg(common + '1', imgfilename0);
        }
        break;
    }
    common = 'eb' +  ("00" +  i).slice(-2);
    for (j = 0; j <= earthBeads; j++) {
      putimg(common + j, imgfilename1);
    }
    putimg(common + Math.min(erth.shift(), earthBeads), imgfilename0);
  }
 
}
 
//
// Undo
//
function undosoroban() {
  playsound();
  redoBuffer.push(encodeAbacus());
  document.getElementById("REDO").disabled=false;
  data = undoBuffer.pop();
  if (undoBuffer.length == 0) {
    document.getElementById("UNDO").disabled=true;
  }
  ary = data.split(':');
  setsoroban(ary[0], ary[1]);
}
 
//
// Redo
//
function redosoroban() {
  playsound();
  undoBuffer.push(encodeAbacus());
  document.getElementById("UNDO").disabled=false;
  data = redoBuffer.pop();
  if (redoBuffer.length == 0) {
    document.getElementById("REDO").disabled=true;
  }
  ary = data.split(':');
  setsoroban(ary[0], ary[1]);
}
 
//
// Generate internal-rep from field (/[uVWX]+:[0-5]+/)
//
function encodeAbacus() {
  let heavenWork = '';
  let earthWork = '';
  let result = heavenWork + ':' + earthWork;
  for (i = 0; i < digitsoroban; i++) {
    common = 'hb' +  ("00" +  i).slice(-2);
    if (heavenBeads == 2) {
      if (document.images[common+'0'].src.indexOf(imgfilenameU) >= 0) {
        heavenWork = heavenWork + 'X';
      } else if (document.images[common+'0'].src.indexOf(imgfilename0) >= 0) {
        heavenWork = heavenWork + 'W';
      } else if (document.images[common+'1'].src.indexOf(imgfilename0) >= 0) {
        heavenWork = heavenWork + 'V';
      } else {
        heavenWork = heavenWork + 'u';
      }
    } else {
      if (document.images[common+'0'].src.indexOf(imgfilename0) >= 0) {
        heavenWork = heavenWork + 'V';
      } else {
        heavenWork = heavenWork + 'u';
      }
    }
    common = 'eb' +  ("00" +  i).slice(-2);
    j = 0;
    while (document.images[common+j].src.indexOf(imgfilename1) >= 0) {
      j++;
    }
    earthWork = earthWork + j;
  }
  return heavenWork+':'+earthWork;
 
}
 
//
// Draw field (number of heaven beads, number of earth beads, digits, separator digits)
//
function drawAbacus(numOf5s, numOf1s, numOfDigits, numOfClusters, unitsLabel) {
  let pointOffset = Math.trunc(numOfDigits / 2)  % numOfClusters;
  heavenBeads = numOf5s;
  earthBeads = numOf1s;
  digitsoroban = numOfDigits;
  digitclusters = numOfClusters;
  let html = "<TABLE BORDER='0' CELLPADDING='0' CELLSPACING='0' STYLE='border:16px ridge brown;background-color:#cccccc;'>\n";
  html += "<TR ALIGN='center' VALIGN='bottom'><TD NOWRAP>\n";
  for (let j = 0; j <= numOf5s; j++) {		// 5 beads  mv("hb[00][0-2]")
    for (let i = 0; i < numOfDigits; i++) {
      html += "<A HREF='JavaScript:mv(";
      html += '"hb' + ("00" +  i).slice(-2) + j + '");';	// i=1(A), i=2(B), ...
      html += "'>";			// <A HREF='JavaScript:mv('hb[00][0-2]');'><IMG NAME='hb[00][0-2]' src='./soroban1' BORDER='0' VSPACE='0' HSPACE='0'></a><BR>.....
      html += "<IMG NAME='hb" + ("00" +  i).slice(-2) + j + "' src='";
      if (j < numOf5s) {
        html += resourcedir + imgfilename1;		//tama
      } else {
        html += resourcedir + imgfilename0;		//jiku
      }
      html += "' BORDER='0' VSPACE='0' HSPACE='0'></a>";
    }
    html += "<BR>\n";
  }
  html += "</TD>\n</TR>\n<TR ALIGN='center' VALIGN='middle'>\n";
  if (numOf5s == 2) {
    beam = makeBeamImage(numOfDigits, unitsLabel);
    html += "<TD NOWRAP STYLE='background-color:black;'>";
    html += "<IMG src='" + beam + "' BORDER='0' VSPACE='0' HSPACE='0'>";
    html += "</TD>\n</TR>\n<TR ALIGN='center' VALIGN='top'>\n";
  } else {
    html += "<TD NOWRAP STYLE='background-color:black;'>";
    for (let i = 0; i < numOfDigits; i++) {
      html += "<IMG src='";
      if ((i - pointOffset) % numOfClusters == 0) {
        html += resourcedir + imgfilenameB1;		// bar with dot
      } else {
        html += resourcedir + imgfilenameB0;		// bar without dot
      }
      html += "' BORDER='0' VSPACE='0' HSPACE='0'>";
    }
    html += "</TD>\n</TR>\n<TR ALIGN='center' VALIGN='top'>\n";
  }
  html += "<TD NOWRAP>";
  for (let j = 0; j <= numOf1s; j++) {					// 1 beads  mv("eb[00][0-4]")
    for (let i = 0; i < numOfDigits; i++) {
      html += "<A HREF='JavaScript:mv(";
      html += '"eb' + ("00" +  i).slice(-2) + j + '");';
      html += "' >";
      html += "<IMG NAME='eb" + ("00" +  i).slice(-2) + j + "' src='";
      if (j > 0) {
        html += resourcedir + imgfilename1;		// tama
      } else {
        html += resourcedir + imgfilename0;		// jiku
      }
      html += "' BORDER='0' VSPACE='0' HSPACE='0'></a>";
    }
    html += "<BR>\n";
  }
  html += "</TD>\n</TR>\n</TABLE>\n";
// Index characters
  html += "<TABLE BORDER='0' CELLPADDING='0' CELLSPACING='0'>\n";
  html += "<TR ALIGN='center' VALIGN='top'>\n<TD NOWRAP>\n";
  for (let i = 0; i < numOfDigits; i++) {
    html += "<INPUT TYPE='text' NAME='IDX" + String.fromCharCode(64 + i) + "' SIZE='1' VALUE='" + String.fromCharCode(65+i) + "' MAXLENGTH='1' DISABLED='DISABLED' STYLE='font-size:20px;line-height:100%;width:50px;border:0 solid white;text-align:center;'>";
  }
  html += "</TD>\n</TR>\n</TABLE>\n";
//  alert(html);
  document.getElementById("sorofield").innerHTML = html;
 }
 
//
 
//
// Play sound
//
function playsound(sourcename) {
  if (soundFlag) {
    document.getElementById("se_soroban").currentTime = 0;
    document.getElementById("se_soroban").play();
  }
}
 
//
// Play sound (Clear)
//
function playsoundClear(sourcename) {
  if (soundFlag) {
    document.getElementById("se_sorobanClear").currentTime = 0;
    document.getElementById("se_sorobanClear").play();
  }
}
 
//
// Generate internal-rep from /[0-9]+/ format (short-hand rep. used in the tutorial doc.)
 
function interpret(num) {
      num = num.replace(/ +/g, '');
      num = num + '0'.repeat(digitsoroban);     // benevolent process
      num = num.split('');
      let hvn = '';
      let erth = '';
      for (i = 0; i < digitsoroban; i++) {
        switch (num[i]) {
          case '0' :
            hvn = hvn + 'u';
            erth = erth + '0';
            break;
          case '1' :
            hvn = hvn + 'u';
            erth = erth + '1';
            break;
          case '2' :
            hvn = hvn + 'u';
            erth = erth + '2';
            break;
          case '3' :
            hvn = hvn + 'u';
            erth = erth + '3';
            break;
          case '4' :
            hvn = hvn + 'u';
            erth = erth + '4';
            break;
          case '5' :
            hvn = hvn + 'V';
            erth = erth + '0';
            break;
          case '6' :
            hvn = hvn + 'V';
            erth = erth + '1';
            break;
          case '7' :
            hvn = hvn + 'V';
            erth = erth + '2';
            break;
          case '8' :
            hvn = hvn + 'V';
            erth = erth + '3';
            break;
          case '9' :
            hvn = hvn + 'V';
            erth = erth + '4';
            break;
          default :
 
        }
      }
 
       return hvn + ':' + erth;
 
    }
 
 
 
 
function soundToggle() {
  let elem = document.getElementById("soundFlag");
  soundFlag = elem.checked;
}
 
function makeBeamImage(numOfRods, unitsLabel) {
    let unitWidth = 50;
    let unitHeight = 20;
    let canvas = document.createElement("canvas");
    canvas.width = numOfRods * unitWidth;
    canvas.height = unitHeight;
    let ctx = canvas.getContext("2d");
    ctx.font = "16px 'Baoli SC', serif";
    let metric = ctx.measureText("壱");
    let baseline = unitHeight * 0.7;
    ctx.fillStyle = "white";
    ctx.fillRect(0, 0, numOfRods * unitWidth, unitHeight);
    ctx.beginPath();
    ctx.fillStyle = "black";
    ctx.lineWidth = 3;
    ctx.moveTo(0, 0);
    ctx.lineTo(unitWidth * numOfRods, 0);
    ctx.moveTo(0, unitHeight);
    ctx.lineTo(unitWidth * numOfRods, unitHeight);
    ctx.stroke();
    for (let i = 0; i < numOfRods; i++) {
      ctx.fillText(unitsLabel.substr(i, 1),
        (i * unitWidth) + (unitWidth / 2) - (ctx.measureText(unitsLabel.substr(i, 1)).width / 2),
        baseline);
    }
    return canvas.toDataURL();
}

y HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=yes">
<meta name="keywords" content="算盤,JavaScript">
<meta name="originalAuthor" content="中川雅央(滋賀大学),Masao NAKAGAWA">
<meta name="modifiedBy" content="Axel Cotón Gutiérrez">
<link rel="icon" href="soroban/sorobangreen.jpeg">
<title>Soroban Viewer</title>
<style>
  #number-display {
    font-size: 48px;
    margin-top: 20px;
  }
</style>
</head>
<body onload="drawAbacus(1, 4, 1);">
  <form>
    <div style="float: right;">
 
    </div>
    <div id="cuenta-movida">A</div>
    <div id="prueba">b</B></div>
 
  </form>
  <form>
    <div align="center">
      <br>
      <input type="button" name="Resetear" value="Resetar" style="font-size:12pt;" onclick="resetsoroban('', '');">
      <input type="button" id="UNDO" name="Deshacer" value="<< Deshacer" style="font-size:12pt;" disabled="true" onclick="undosoroban('', '');">
      <input type="button" id="REDO" name="Rehacer" value="Rehacer >>" style="font-size:12pt;" disabled="true" onclick="redosoroban('', '');">
      <input type="checkbox" id="soundFlag" checked="checked" onclick="soundToggle();">Sonido
    <audio id="se_soroban" preload="auto">
      <source src="./soroban/soroban.mp3" type="audio/mp3">
    </audio>
    <audio id="se_sorobanClear" preload="auto">
      <source src="./soroban/sorobanClear.mp3" type="audio/mp3">
    </audio>
      <br>
      <br>
    </div>
 
    <div align="center" id="sorofield"></div>
 
  </form>
</body>
</html>
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Alejandro
Val: 1.448
Plata
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Número del Soroban

Publicado por Alejandro (532 intervenciones) el 31/05/2023 21:59:26
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
Parece que la función que mencionas es para dar un numero decimal y convertirlo al tablero por lo que habría que programar un función inversa.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil

Número del Soroban

Publicado por Axel (2 intervenciones) el 01/06/2023 09:31:40
Gracias, por la respuesta, es una de las funciones internas de los tutoriales que no había quitado. No es lo que busco pero puede servir para otras cosas en el futuro.

Lo que busco es más simple y es que lea el número que hay en el ábaco/soroban, teniendo en cuenta que la función mov(name) establece claramente que cuenca se mueve. Quizás usando la función encodeababacus o la setsoroban.

Si alguien sabe como hacerlo directamente con el código actual sin hacer función inversa, será bienvenido. ;)
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
Imágen de perfil de Alejandro
Val: 1.448
Plata
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

Número del Soroban

Publicado por Alejandro (532 intervenciones) el 01/06/2023 19:31:29
  • Alejandro se encuentra ahora conectado en el
  • chat de PHP
encodeababacus() es para obtener el estado del tablero y se usa para poder deshacer o rehacer
setsoroban() posiciona las fichas al deshacer o rehacer
mv() mueve la ficha

El programa no tiene instrucciones para obtener el numero digital. Necesitas usar encodeabacus() para obtener el estado del tablero y crear una función para convertir eso a numero decimal que se corresponde a hacer lo inverso de interpret()
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar