Quellcode durchsuchen

updated sources and readme

Jose Ortiz vor 9 Jahren
Ursprung
Commit
883681d285
17 geänderte Dateien mit 3261 neuen und 915 gelöschten Zeilen
  1. BIN
      Guia para el instructor.docx
  2. 2
    339
      README.md
  3. 1773
    0
      Testing.html
  4. 703
    0
      Testing.md
  5. 0
    1
      Testing.pro
  6. 7
    0
      UnitTests/UnitTests.pro
  7. 130
    0
      UnitTests/main.cpp
  8. 265
    42
      functions.cpp
  9. 4
    292
      functions.h
  10. 0
    1
      images.qrc
  11. BIN
      imagesTesting.zip
  12. 48
    1
      main.cpp
  13. 278
    57
      mainwindow.cpp
  14. 45
    152
      mainwindow.h
  15. 4
    3
      mainwindow.ui
  16. 1
    1
      secondwindow.cpp
  17. 1
    26
      secondwindow.h

BIN
Guia para el instructor.docx Datei anzeigen


+ 2
- 339
README.md
Datei-Diff unterdrückt, da er zu groß ist
Datei anzeigen


+ 1773
- 0
Testing.html
Datei-Diff unterdrückt, da er zu groß ist
Datei anzeigen


+ 703
- 0
Testing.md Datei anzeigen

@@ -0,0 +1,703 @@
1
+[English](#markdown-header-testing-and-unit-testing) | [Español](#markdown-header-pruebas-y-pruebas-unitarias)
2
+
3
+#Pruebas y pruebas unitarias
4
+
5
+![main1.png](images/main1.png)
6
+![main2.png](images/main2.png)
7
+![main3.png](images/main3.png)
8
+
9
+
10
+Como habrás aprendido en experiencias de laboratorio anteriores, lograr que un programa compile es solo una pequeña parte de programar. El compilador se encargará de decirte si hubo errores de sintaxis, pero no podrá detectar errores en la lógica del programa. Es muy importante el probar las funciones del programa para validar que producen los resultados correctos y esperados.
11
+
12
+Una manera de hacer estas pruebas es “a mano”, esto es, corriendo el programa múltiples veces, ingresando valores representativos (por medio del teclado) y visualmente verificando que el programa devuelve los valores esperados. Una forma más conveniente es implementar funciones dentro del programa cuyo propósito es verificar que otras funciones produzcan resultados correctos. En esta experiencia de laboratorio practicarás ambos métodos de verificación.
13
+
14
+##Objetivos:
15
+
16
+1. Validar el funcionamiento de varias funciones haciendo pruebas "a mano".
17
+2. Crear pruebas unitarias para validar funciones, utilizando la función `assert` 
18
+
19
+
20
+
21
+##Pre-Lab:
22
+
23
+Antes de llegar al laboratorio debes:
24
+
25
+1. Haber repasado los conceptos básicos relacionados a pruebas y pruebas unitarias.
26
+
27
+2. Haber repasado el uso de la función `assert` para hacer pruebas.
28
+
29
+3. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
30
+
31
+4. Haber tomado el quiz Pre-Lab que se encuentra en Moodle.
32
+
33
+---
34
+
35
+---
36
+
37
+##Haciendo pruebas a una función. 
38
+
39
+Cuando probamos la validez de una función debemos probar casos que activen los diversos resultados de la función. 
40
+
41
+---
42
+
43
+**Ejemplo 1:** si fueras a validar una función `esPar(unsigned int n)` que determina si un entero positivo *n* es par, deberías hacer pruebas a la función tanto con números pares como números impares. Un conjunto adecuado de pruebas para dicha función podría ser:
44
+
45
+
46
+|   Prueba   | Resultado esperado |
47
+|------------|--------------------|
48
+| `esPar(8)` | true               |
49
+| `esPar(7)` | false                   |
50
+
51
+---
52
+
53
+**Ejemplo 2:** Digamos que un amigo ha creado una función `unsigned int rangoEdad(unsigned int edad)` que se supone que devuelva 0 si la edad está entre 0 y 5 (inclusive), 1 si la edad está entre 6 y 18 inclusive, y 2 si la edad es mayor de 18. Una fuente común de errores en funciones como esta son los valores próximos a los límites de cada rango, por ejemplo, el número 5 se presta para error si el programador  no usó una comparación correcta. Un conjunto adecuado  de pruebas para la función `rangoEdad` sería:
54
+
55
+|      Prueba     | Resultado esperado |
56
+|-----------------|--------------------|
57
+| `rangoEdad(5)`  |                  0 |
58
+| `rangoEdad(2)`  |                  0 |
59
+| `rangoEdad(6)`  |                  1 |
60
+| `rangoEdad(18)` |                  1 |
61
+| `rangoEdad(17)` |                  1 |
62
+| `rangoEdad(19)` |                  2 |
63
+| `rangoEdad(25)` |                  2 |
64
+
65
+---
66
+
67
+###La función `assert`
68
+
69
+
70
+La función `assert(bool expression)` se puede utilizar como herramienta rudimentaria para validar de funciones. `assert` tiene un funcionamiento muy sencillo y poderoso.  Si la expresión que colocamos entre los paréntesis de `assert` es *cierta* la función permite que el programa continúe con la próxima instrucción. De lo contrario, si la expresión que colocamos entre los paréntesis es *falsa*, la función `assert` hace que el programa termine e imprime un mensaje al terminal que informa al usuario sobre la instrucción de `assert` que falló. 
71
+
72
+Por ejemplo, el siguiente programa correrá de principio a fin sin problemas pues todos las expresiones incluidas en los paréntesis de los asserts evalúan a *true*.
73
+
74
+---
75
+
76
+```cpp
77
+#include <iostream>
78
+#include <cassert>
79
+using namespace std;
80
+
81
+int main() {
82
+   int i = 10, j = 15;
83
+   assert(i == 10);
84
+   assert(j == i + 5);
85
+   assert(j != i);
86
+   assert( (j < i) == false);
87
+   cout << "Eso es todo, amigos!" << endl;
88
+   return 0;
89
+}
90
+
91
+```
92
+
93
+**Figura 1.** Ejemplo de programa que pasa todas las pruebas de `assert`.
94
+
95
+---
96
+
97
+El siguiente programa no correrá hasta el final pues el segundo `assert` (`assert(j == i);`)  contiene una expresión  (`j==i`) que evalúa a *false*.
98
+
99
+---
100
+
101
+```cpp
102
+
103
+#include <iostream>
104
+#include <cassert>
105
+using namespace std;
106
+
107
+int main() {
108
+   int i = 10, j = 15;
109
+   assert(i == 10);
110
+   assert(j == i);
111
+   assert(j != i);
112
+   assert( (j < i) == false);
113
+   cout << "Eso es todo, amigos!" << endl;
114
+   return 0;
115
+}
116
+
117
+```
118
+
119
+**Figura 2.** Ejemplo de programa que no "pasa" una prueba de `assert`.
120
+
121
+---
122
+
123
+Al correr el pasado programa, en lugar de obtener la frase `”Eso es todo amigos!”` en el terminal, obtendremos un mensaje como el siguiente:
124
+
125
+`Assertion failed: (j == i), function main, file ../programa01/main.cpp, line 8.`
126
+
127
+El programa no ejecuta más instrucciones después de la línea 8.
128
+
129
+####¿Cómo usar assert para validar funciones?
130
+
131
+Digamos que deseas automatizar la validación de la función `rangoEdad`. Un forma de hacerlo es crear una función que llame a la función `rangoEdad` con diversos argumentos y verifique que lo devuelto concuerde con el resultado esperado. Si incluimos cada comparación entre lo devuelto por `rangoEdad` y el resultado esperado dentro de un `assert`, obtenemos una función que se ejecuta de principio a fin solo si todas las invocaciones devolvieron el resultado esperado.
132
+
133
+---
134
+
135
+```cpp
136
+void test_rangoEdad() {
137
+   assert(rangoEdad(5) == 0);
138
+   assert(rangoEdad(2) == 0);
139
+   assert(rangoEdad(6) == 1);
140
+   assert(rangoEdad(18) == 1);
141
+   assert(rangoEdad(17) == 1);
142
+   assert(rangoEdad(19) == 2);
143
+   assert(rangoEdad(25) == 2);
144
+   cout << "rangoEdad passed all tests!!!" << endl;
145
+}
146
+```
147
+
148
+**Figura 3.** Ejemplo de una función para pruebas usando `assert`.
149
+
150
+
151
+---
152
+
153
+---
154
+
155
+
156
+##Sesión de laboratorio:
157
+
158
+###Ejercicio 1: Diseñar pruebas "a mano"
159
+
160
+En este ejercicio practicarás cómo diseñar pruebas para validar funciones, utilizando solamente la descripción de la función y la interfaz que se usa para interactuar con la función. 
161
+
162
+El ejercicio **NO requiere programación**, solo requiere que entiendas la descripción de la función, y tu habilidad para diseñar pruebas. Este ejercicio y el Ejercicio 2 son una adaptación del ejercicio en [1].
163
+
164
+**Ejemplo 3.** Supón que una amiga te provee un programa. Ella asegura que el programa resuelve el siguiente problema: 
165
+
166
+`"dados tres enteros, despliega el valor máximo".` 
167
+
168
+Supón que el programa tienen una interfaz como la siguiente:
169
+
170
+---
171
+
172
+![figure4.png](images/figure4.png)
173
+
174
+**Figura 4** - Interfaz de un programa para hallar el valor máximo entre tres enteros.
175
+
176
+---
177
+
178
+Podrías determinar si el programa provee resultados válidos **sin analizar el código fuente**. Por ejemplo, podrías intentar los siguientes casos:
179
+
180
+* a = 4, b = 2, c = 1; resultado esperado: 4
181
+* a = 3, b = 6, c = 2; resultado esperado: 6
182
+* a = 1, b = 10, c = 100; resultado esperado: 100
183
+
184
+Si alguno de estos tres casos no da el resultado esperado, el programa de tu amiga no funciona. Por otro lado, si los tres casos funcionan, entonces el programa tiene una probabilidad alta de estar correcto.
185
+
186
+####Funciones para validar
187
+
188
+En este ejercicio estarás diseñando pruebas que validen varias versiones de las funciones que se describen abajo. Cada una de las funciones tiene cuatro versiones, "Alpha", "Beta", "Gamma" y "Delta".
189
+
190
+
191
+* **3 Sorts:** una función que recibe tres "strings" y los ordena en orden lexicográfico (alfabético). Por ejemplo, dados `jirafa`, `zorra`, y `coqui`, los ordena como: `coqui`, `jirafa`, y `zorra`.  Para simplificar el ejercicio, solo usaremos "strings" con letras minúsculas. La Figura 5 muestra la interfaz de esta función. Nota que hay un menú para seleccionar la versión implementada.
192
+
193
+  ---
194
+
195
+
196
+    ![figure5.png](images/figure5.png)
197
+
198
+    **Figura 5** - Interfaz de la función `3 Sorts`.
199
+
200
+  ---
201
+
202
+
203
+
204
+* **Dice:** cuando el usuario marca el botón `Roll them!`, el programa genera dos números aleatorios entre 1 y 6. El programa informa la suma de los números aleatorios. 
205
+
206
+  ---
207
+
208
+    ![figure6.png](images/figure6.png)
209
+
210
+    **Figura 6** - Interfaz de la función `Dice`.
211
+
212
+  ---
213
+
214
+* **Rock, Paper, Scissors:** cada uno de los jugadores entra su jugada y el programa informa quién ganó. La Figura 7 muestra las opciones en las que un objeto le gana a otro. La interfaz del juego se muestra en la  Figura 8.
215
+
216
+  ---
217
+
218
+    ![figure7.jpg](images/figure7.jpg)
219
+
220
+    **Figura 7** - Formas de ganar en el juego "Piedra, papel y tijera".
221
+
222
+  ---
223
+
224
+    ![figure8.png](images/figure8.png)
225
+
226
+    **Figura 8** - Interfaz de la función `Rock, Paper, Scissors`.
227
+
228
+  ---
229
+
230
+
231
+* **Zulu time:** Dada una hora en tiempo Zulu (Hora en el Meridiano de Greenwich) y la zona militar en la que el usuario desea saber la hora, el programa muestra la hora en esa zona. El formato para el dato de entrada es en formato de 23 horas `####`, por ejemplo `2212` sería las 10:12 pm. La lista de zonas militares válidas la puedes encontrar en  http://en.wikipedia.org/wiki/List_of_military_time_zones. Lo que sigue son ejemplos de cómo deben ser los resultados del programa:
232
+
233
+  * Dada hora Zulu 1230 y zona A (UTC+1), el resultado debe ser 1330.
234
+  * Dada hora Zulu 1230 y zona N (UTC-1), el resultado debe ser 1130.
235
+  * Puerto Rico está en la zona militar Q (UTC-4), por lo tanto, cuando es 1800 en hora Zulu, son las 1400 en Puerto Rico.
236
+  
237
+  ---
238
+
239
+    ![figure9.png](images/figure9.png)
240
+
241
+    **Figura 9** - Interfaz de la función `Zulu time`.
242
+
243
+  ---
244
+
245
+####Instrucciones
246
+
247
+1. Para cada una de las funciones descritas arriba, escribe en tu libreta las pruebas que harás para determinar la validez de cada implementación (Alpha, Beta, Gamma y Delta). Para cada función, piensa en los errores lógicos que el programador pudo haber cometido y escribe pruebas que determinen si se cometió ese error. Para cada prueba, escribe los valores que utilizarás y el resultado que esperas obtener.
248
+
249
+  Por ejemplo, puedes organizar tus respuestas en una tabla como la que sigue:
250
+
251
+  ---
252
+
253
+
254
+  | 3 Sorts |                           |                           |           |            |            |
255
+  |---------|---------------------------|---------------------------|-----------|------------|------------|
256
+  | Num     | Prueba                    | Result Alpha              | Res. Beta | Res. Gamma | Res. Delta |
257
+  | 1       | "alce", "coyote", "zorro" | "alce", "coyote", "zorro" | ....      | ....       |            |
258
+  | 2       | "alce", "zorro", "coyote" | "zorro", "alce", "coyote" | ....      | ....       |            |
259
+  | ....    | ....                      | ....                      | ....      | ....       | ....       |
260
+
261
+  **Figura 10** - Tabla para organizar los resultados de las pruebas.
262
+
263
+  ---
264
+
265
+  Puedes ver ejemplos de cómo organizar tus resultados [aquí](http://i.imgur.com/ggDZ3TQ.png) y [aquí](http://i.imgur.com/rpApVqm.png). 
266
+
267
+
268
+
269
+###Ejercicio 2: Hacer pruebas "a mano"
270
+
271
+El proyecto `testing` implementa varias versiones de cada una de las cuatro funciones simples que se decribieron en el Ejercicio 1. Algunas o todas las implementaciones pueden estar incorrectas. Tu tarea es, usando las pruebas que diseñaste en el Ejercicio 1, probar las versiones de cada función para  determinar cuáles de ellas, si alguna, están  implementadas correctamente.
272
+
273
+Este ejercicio **NO requiere programación**, debes hacer las pruebas **sin mirar el código.**
274
+
275
+####Instrucciones
276
+
277
+1. Carga a Qt el proyecto `Testing`  haciendo doble "click" en el archivo `Testing.pro` en el directorio `Documents/eip/Testing` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/testing` para descargar la carpeta `Testing` a tu computadora.
278
+
279
+2. Configura el proyecto y corre el programa. Verás una pantalla similar a la siguiente:
280
+  
281
+  ---
282
+
283
+    ![figure11.png](images/figure11.png)
284
+
285
+    **Figura 11** - Ventana para seleccionar la función que se va a probar.
286
+
287
+  ---
288
+
289
+3. Selecciona el botón de `3 Sorts` y obtendrás la interfaz de la Figura 5.
290
+
291
+4. La "Version Alpha" en la caja indica que estás corriendo la primera versión del algoritmo `3 Sorts`. Usa las pruebas que escribiste en el Ejercicio 1 para validar la "Version Alpha". Luego, haz lo mismo para las versiones Beta, Gamma y Delta. Escribe cuáles son las versiones correctas (si alguna) de la función y porqué. Recuerda que, para cada función, algunas o todas las implementaciones pueden estar incorrectas. Además, especifica cuáles pruebas te permitieron determinar  las  versiones que son incorrectas.
292
+
293
+
294
+
295
+###Ejercicio 3: Usar `assert` para realizar pruebas unitarias
296
+
297
+Hacer pruebas "a mano" cada vez que corres un programa es una tarea que resulta "cansona" bien rápido. En los ejercicios anteriores lo hiciste para unas pocas funciones simples. !Imagínate hacer lo mismo para un programa complejo completo como un buscador o un procesador de palabras!
298
+
299
+Las *pruebas unitarias* ayudan a los programadores a validar códigos y simplificar el proceso de depuración ("debugging") a la vez que evitan la tarea tediosa de hacer pruebas a mano en cada ejecución.
300
+
301
+####Instrucciones:
302
+
303
+1. En el menú de QT, ve a `Build` y selecciona `Clean Project "Testing"`.
304
+
305
+2. Carga a Qt el proyecto `UnitTests`  haciendo doble "click" en el archivo `UnitTests.pro` en el directorio `Documents/eip/Testing` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/testing` para descargar la carpeta `Testing` a tu computadora.
306
+
307
+3. El proyecto solo contiene el archivo de código fuente `main.cpp`. Este archivo contiene cuatro funciones: `fact`, `isALetter`, `isValidTime`, y `gcd`, cuyos resultados son solo parcialmente correctos. 
308
+
309
+  Estudia la descripción de  cada una de las funciones que aparece como comentarios antes el código de la función para saber la tarea que se espera haga la función.
310
+
311
+  Tu tarea es escribir pruebas unitarias para cada una de las funciones para identificar los resultados erróneos. ** No necesitas reescribir las funciones para corregirlas. **
312
+
313
+  Para la función `fact` se provee la función  `test_fact()`  como función de prueba unitaria. Si invocas esta función desde `main`, compilas y corres el programa debes obtener un mensaje como el siguiente:
314
+
315
+    `Assertion failed: (fact(2) == 2), function test_fact, file ../UnitTests/ main.cpp, line 69.`
316
+
317
+  Esto es suficiente para saber que la función `fact` NO está correctamente implementada. 
318
+
319
+4. Nota que, al fallar la prueba anterior, el programa no continuó su ejecución. Para poder probar el código que escribirás, comenta la invocación de `test_fact()` en `main`.
320
+
321
+5. Escribe una prueba unitaria llamada `test_isALetter` para la función `isALetter`. En la prueba unitaria escribe varias  afirmaciones ("asserts") para probar algunos datos de entrada y sus valores esperados (mira la función `test_fact` para que te inspires). Invoca `test_isALetter` desde `main` y ejecuta tu programa. Si la función `isALetter` pasa las pruebas que escribiste, continúa escribiendo "asserts" y ejecutando tu programa hasta que alguno de los `asserts` falle. 
322
+
323
+6. Comenta la invocación de `test_isALetter` en `main` para que puedas continuar con las otras funciones.
324
+
325
+7. Repite los pasos 5 y 6 paras las otras dos funciones, `isValidTime` y `gcd`.  Recuerda que debes llamar a cada una de las funciones de prueba unitaria desde `main` para que corran. 
326
+
327
+---
328
+
329
+---
330
+
331
+##Entregas
332
+
333
+1. Utiliza "Entrega 1" en Moodle para entregar la tabla con las pruebas que diseñaste en el Ejercicio 1 y que completaste en el Ejercicio 2 con los resultados de las pruebas de las funciones.
334
+
335
+2. Utiliza "Entrega 2" en Moodle para entregar el archivo `main.cpp` que contiene las funciones `test_isALetter`, `test_isValidTime`, `test_gcd` y sus invocaciones. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.
336
+
337
+---
338
+
339
+---
340
+
341
+## Referencias
342
+
343
+[1] http://nifty.stanford.edu/2005/TestMe/
344
+
345
+---
346
+
347
+---
348
+
349
+---
350
+
351
+
352
+
353
+[English](#markdown-header-testing-and-unit-testing) | [Español](#markdown-header-pruebas-y-pruebas-unitarias)
354
+
355
+#Testing and Unit Testing
356
+
357
+![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/D0laI5r.png)
358
+![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/ggDZ3TQ.png)
359
+![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/V6xFo00.png)
360
+
361
+
362
+
363
+As you have learned in previous labs, getting a program to compile is only a minor part of programming. The compiler will tell you if there are syntactical errors, but it isn't capable of detecting logical problems in your program. It's very important to test the program's functions to validate that they produce correct results.
364
+
365
+These tests can be performed by hand, this is, running the program multiple times, providing representative inputs and visually checking that the program outputs correct results. A more convenient way is to implement functions in the program whose sole purpose is to validate that other functions are working correctly. In this lab you will be practicing both testing methods.
366
+
367
+
368
+##Objectives:
369
+
370
+1. Design tests to validate several programs “by-hand”, then use these tests to determine if the program works as expected. 
371
+2. Create unit tests to validate functions, using the `assert` function.
372
+
373
+
374
+##Pre-Lab:
375
+
376
+Before you get to the laboratory you should have:
377
+
378
+1. Reviewed the basic concepts related to testing and unit tests.
379
+
380
+2. Reviewed how to use the `assert` function to validate another function.
381
+
382
+3. Studied the concepts and instructions for this laboratory session.
383
+
384
+4. Taken the Pre-Lab quiz available in Moodle.
385
+
386
+---
387
+
388
+---
389
+
390
+## Testing a function
391
+
392
+When we test a function's validity we should test cases that activate the various results the function could return.
393
+
394
+---
395
+
396
+**Example 1:** if you were to validate the function `isEven(unsigned int n)` that determines if a positive integer *n* is even, you should test the function using even and odd numbers. A set of tests for that function could be:
397
+
398
+
399
+|     Test     | Expected Result |
400
+|--------------|-----------------|
401
+| `isEven(8)`  | true            |
402
+| `isEven(7)`  | false           |
403
+
404
+---
405
+
406
+**Example 2:** Suppose that a friend has created a function `unsigned int ageRange(unsigned int age)` that is supposed to return 0 if the age is between 0 and 5 (inclusive), 1 if the age is between 6 and 18 inclusive, and 2 if the age is above 18. A common source of errors in functions like this one are the values near to the limits of each range, for example, the number 5 can cause errors if the programmer did not use a correct comparison. One good set of tests for the `ageRange` function would be:
407
+
408
+|      Test      | Expected Result |
409
+|----------------|-----------------|
410
+| `ageRange(5)`  |               0 |
411
+| `ageRange(2)`  |               0 |
412
+| `ageRange(6)`  |               1 |
413
+| `ageRange(18)` |               1 |
414
+| `ageRange(17)` |               1 |
415
+| `ageRange(19)` |               2 |
416
+| `ageRange(25)` |               2 |
417
+
418
+---
419
+
420
+###`Assert` Function:
421
+
422
+The `assert(bool expression)` function can be used as a rudimentary tool to validate functions. `assert` has a very powerful yet simple functionality. If the expression that we place between the `assert` parenthesis is *true*, the function allows the program to continue onto the next instruction. Otherwise, if the expression we place between the parenthesis is *false*, the `assert` function causes the program to terminate and prints an error message on the terminal that informs the user about the `assert` instruction that failed.
423
+
424
+For example, the following program will run from start to finish without problems since every expression included in the assert's parentheses evaluates to *true*.
425
+
426
+---
427
+
428
+```cpp
429
+#include <iostream>
430
+#include <cassert>
431
+using namespace std;
432
+
433
+int main() {
434
+   int i = 10, j = 15;
435
+   assert(i == 10);
436
+   assert(j == i + 5);
437
+   assert(j != i);
438
+   assert( (j < i) == false);
439
+   cout << "That's all, folks!" << endl;
440
+   return 0;
441
+}
442
+
443
+```
444
+
445
+**Figure 1.** Example of a program that passes all of the `assert` tests.
446
+
447
+---
448
+
449
+The following program will not run to completion because the second `assert` (`assert(j == i);`) contains an expression (`j==i`) that evaluates to *false*.
450
+
451
+---
452
+
453
+```cpp
454
+
455
+#include <iostream>
456
+#include <cassert>
457
+using namespace std;
458
+
459
+int main() {
460
+   int i = 10, j = 15;
461
+   assert(i == 10);
462
+   assert(j == i);
463
+   assert(j != i);
464
+   assert( (j < i) == false);
465
+   cout << "That's all, folks!" << endl;
466
+   return 0;
467
+}
468
+
469
+```
470
+
471
+**Figure 2.** Example of a program that does not pass an `assert` test.
472
+
473
+---
474
+
475
+When the program is run, instead of getting the phrase `”That's all, folks!”` in the terminal, we will obtain something like:
476
+
477
+`Assertion failed: (j == i), function main, file ../program01/main.cpp, line 8.`
478
+
479
+The program will not execute the remaining instructions after line 8.
480
+
481
+#### How to use assert to validate functions?
482
+
483
+Suppose that  you want to automate the validation of the `ageRange`. One way to do it is by  implementing and calling a function that calls the `ageRange` function with different arguments and verifies that each returned value is equal to  the expected result. If the `ageRange` function returns a value that is not expected, the testing function aborts the program and reports the test that failed. The following illustrates a function to test the `ageRange` function. Observe that it consists of one assert per each of the tests we had listed earlier. 
484
+
485
+---
486
+
487
+```cpp
488
+void test_ageRange() {
489
+   assert(ageRange(5) == 0);
490
+   assert(ageRange(2) == 0);
491
+   assert(ageRange(6) == 1);
492
+   assert(ageRange(18) == 1);
493
+   assert(ageRange(17) == 1);
494
+   assert(ageRange(19) == 2);
495
+   assert(ageRange(25) == 2);
496
+   cout << "ageRange passed all tests!!!" << endl;
497
+}
498
+```
499
+
500
+**Figure 3.** Example of a test function using `assert`.
501
+
502
+
503
+---
504
+
505
+---
506
+
507
+##Laboratory Session:
508
+
509
+###Exercise 1: Designing tests by hand
510
+
511
+In this exercise you will practice how to design tests to validate functions, using only the function's description and the graphical user interface that is used interact with the function.
512
+
513
+The exercise **DOES NOT require programming**, it only requires that you understand the function’s description, and your ability to design tests. This exercise and Exercise 2 are an adaptation of the exercise in [1].
514
+
515
+**Example 3** Suppose that a friend provides you with a program. She makes sure the program solves the following problem:
516
+
517
+`"given three integers, it displays the max value".`
518
+
519
+Suppose that the program has an interface like the following:
520
+
521
+---
522
+
523
+![figure4.png](images/figure4.png)
524
+
525
+**Figure 4** - Interface for a program that finds the max value out of three integers.
526
+
527
+---
528
+
529
+You could determine if the program provides valid results **without analyzing the source code**. For example, you could try the following cases:
530
+
531
+* a = 4, b = 2, c = 1; expected result: 4
532
+* a = 3, b = 6, c = 2; expected result: 6
533
+* a = 1, b = 10, c = 100; expected result: 100
534
+
535
+If one of these three cases does not have the expected result, your friend's program does not work. On the other hand, if the three cases work, then the program has a high probability of being correct.
536
+
537
+
538
+####Functions to validate
539
+
540
+In this exercise you will be designing tests to validate various versions of the functions that are described below. Each one of the functions has four versions, "Alpha", "Beta", "Gamma" and "Delta".
541
+
542
+* **3 Sorts:** a function that receives three strings and orders them in lexicographic (alphabetical) order. For example, given `giraffe`, `fox`, and `coqui`, it would order them as: `coqui`, `fox`, and `giraffe`. To simplify the exercise, we will be using strings with lowercase **letters**. Figure 5 shows the function's interface. Notice there is a menu to select the implemented version.
543
+
544
+  ---
545
+
546
+    ![figure5.png](images/figure5.png)
547
+
548
+    **Figure 5** - Interface for the `3 Sorts` function.
549
+
550
+  ---
551
+
552
+
553
+* **Dice:** when the user presses the `Roll them!` button, the program generates two random integers between 1 and 6. The program informs the sum of the two random numbers.
554
+
555
+  ---
556
+
557
+    ![figure6.png](images/figure6.png)
558
+
559
+    **Figure 6** - Interface for the `Dice` function.
560
+
561
+  ---
562
+
563
+
564
+* **Rock, Paper, Scissors:** each one of the players enters their play and the program informs who the winner is. Figure 7 shows the options where one object beats the other. The game's interface is shown in Figure 8.
565
+
566
+  ---
567
+
568
+  ![figure7.jpg](images/figure7.jpg)
569
+
570
+  **Figure 7** - Ways to win in "Rock, paper, scissors".
571
+
572
+  ---
573
+
574
+    ![figure8.png](images/figure8.png)
575
+
576
+    **Figure 8** - Interface for the `Rock, Paper, Scissors` function.
577
+
578
+  ---
579
+
580
+
581
+* **Zulu time:** Given a time in Zulu format (time at the Greenwich Meridian) and the military zone in which the user wants to know the time, the program shows the time in that zone. The format for the entry data is in the 24 hour format `####`, for example `2212` would be 10:12pm. The list of valid military zones can be found in http://en.wikipedia.org/wiki/List_of_military_time_zones. The following are examples of some valid results:
582
+
583
+  * Given Zulu time 1230 and zone A (UTC+1), the result should be 1330.
584
+  * Given Zulu time 1230 and zone N (UTC-1), the result should be 1130.
585
+  * Puerto Rico is in military zone Q (UTC-4), therefore, when its 1800 in Zulu time, it's 1400 in Puerto Rico.
586
+
587
+  ---
588
+
589
+    ![figure9.png](images/figure9.png)
590
+
591
+    **Figure 9** - Interface for the `Zulu time` function.
592
+
593
+  ---
594
+
595
+
596
+####Instructions
597
+
598
+1. For each of the functions described above, write in your notebook the tests that you will do to determine the validity of each implementation (Alpha, Beta, Gamma and Delta). For each function, think of the logical errors that the programmer could have made and write tests that determine if these errors were made. For each test, write the values that you will use and the expected result.
599
+
600
+  For example, you could organize your answers in a table like the following:
601
+
602
+
603
+  ---
604
+
605
+
606
+  | 3 Sorts |                           |                           |           |            |            |
607
+  |---------|---------------------------|---------------------------|-----------|------------|------------|
608
+  | Num     | Test                    | Alpha Result              | Beta Result | Gamma Result | Delta Result |
609
+  | 1       | "deer", "coyote", "fox" | "coyote", "deer", "fox" | ....      | ....       |            |
610
+  | 2       | "deer", "fox", "coyote" | "fox", "deer", "coyote" | ....      | ....       |            |
611
+  | ....    | ....                      | ....                      | ....      | ....       | ....       |
612
+
613
+        
614
+  **Figure 10** - Table to organize the test results.
615
+
616
+  ---
617
+
618
+You can see examples of how to organize your results [here](http://i.imgur.com/ggDZ3TQ.png) and [here](http://i.imgur.com/rpApVqm.png).
619
+
620
+
621
+###Exercise 2: Doing tests “by hand”
622
+
623
+The `testing` project implements several versions of each of the four functions that were described in Exercise 1. Some or all of the implementations could be incorrect. Your task is, using the tests you designed in Exercise 1, to test the versions for each function to determine which of them, if any, are implemented correctly.
624
+
625
+This exercise **DOES NOT require programming**, you should make the tests **without looking at the code.**
626
+
627
+####Instructions
628
+
629
+1. Load the `Testing` project onto Qt by double clicking the `Testing.pro` file in the `Documents/eip/Testing` directory on your computer. You can also go to `http://bitbucket.org/eip-uprrp/testing` to downloaded the `Testing` folder on your computer.
630
+
631
+2. Configure the project and run the program. You will see a window similar to the following:
632
+
633
+  ---
634
+
635
+    ![figure11.png](images/figure11.png)
636
+
637
+    **Figure 11** - Window to select the function that will be tested.
638
+
639
+  ---
640
+
641
+3. Select the button for `3 Sorts` and you will obtain the interface in Figure 5.
642
+
643
+4. The "Alpha Version" in the box indicates that you're running the first version of the `3 Sorts` algorithm. Use the tests that you wrote in Exercise 1 to validate the "Alpha Version". Afterwards, do the same with the Beta, Gamma and Delta versions. Write down which are the correct versions of the function (if any), and why. Remember that, for each function, some or all of the implementations could be incorrect. Additionally, specify which tests allowed you to determine the incorrect versions.
644
+
645
+
646
+
647
+###Exercise 3: Using `assert` to make unit tests
648
+
649
+Doing tests by hand each time you run a program is a tiresome task. In the previous exercises you did it for a few simple functions. Imagine doing the same for a complex program like a search engine or a word processor.
650
+
651
+*Unit tests* help programmers validate code and simplify the process of debugging while avoiding having to do these tests by hand in each execution.
652
+
653
+####Instructions:
654
+
655
+1. In the Qt menu, go to `Build` and select `Clean Project "Testing"`.
656
+
657
+2. Load the `UnitTests` project onto Qt by double clicking the `UnitTests.pro` file in the `Documents/eip/Testing` directory on your computer. You can also go to `http://bitbucket.org/eip-uprrp/testing` to download the `Testing` folder on your computer.
658
+
659
+3. The project only contains the source code file `main.cpp`. This file contains four functions: `fact`, `isALetter`, `isValidTime`, and `gcd`, whose results are only partially correct.
660
+
661
+    Study the description of each function that appears as a comment before the function's code to understand the task that the function is supposed to carry out.
662
+
663
+    Your task is to write unit tests for each of the functions to identify the erroneous results. **You do not need to rewrite the functions to correct them.**
664
+
665
+    For the `fact` function, a `test_fact()` is provided as a unit test function. If you invoke the function from `main`, compile and run the program you should obtain a message like the following:
666
+
667
+     `Assertion failed: (fact(2) == 2), function test_fact, file ../UnitTests/ main.cpp, line 69.`
668
+
669
+     This is evidence enough to establish that the `fact` function is NOT correctly implemented.
670
+
671
+4. Notice that, by failing the previous test, the program did not continue its execution. To test the code you will write, comment the `test_fact()` call in `main`.
672
+
673
+5. Write a unit test called `test_isALetter` for the `isALetter` function. Write various asserts in the unit test to try some data and its expected values (use the `test_fact` function for inspiration). Invoke `test_isALetter` from `main` and execute your program. If the `isALetter` function passes the test you wrote, continue writing asserts and executing the program until one of them fails.
674
+
675
+6. Comment the `test_isALetter` call in `main` so you can continue with the other functions.
676
+
677
+7. Repeat the steps in 5 and 6 for the other two functions, `isValidTime` and `gcd`. Remember that you should call each of the unit test functions from `main` for them to run.     
678
+
679
+---
680
+
681
+---
682
+
683
+##Deliverables
684
+
685
+1. Use "Deliverables 1" in Moodle to hand in the table with the tests you designed in Exercise 1 and that you completed in Exercise 2 with the results from the function tests.
686
+
687
+2. Use "Deliverables 2" in Moodle to hand in the `main.cpp` file that contains the `test_isALetter`, `test_isValidTime`, `test_gcd` functions and their calls. Remember to use good programming techniques, include the name of the programmers involved and document your program.
688
+
689
+---
690
+
691
+---
692
+
693
+## References
694
+
695
+[1] http://nifty.stanford.edu/2005/TestMe/
696
+
697
+---
698
+
699
+---
700
+
701
+---
702
+
703
+

+ 0
- 1
Testing.pro Datei anzeigen

@@ -25,4 +25,3 @@ FORMS    += mainwindow.ui
25 25
 
26 26
 RESOURCES += \
27 27
     images.qrc
28
-

+ 7
- 0
UnitTests/UnitTests.pro Datei anzeigen

@@ -0,0 +1,7 @@
1
+TEMPLATE = app
2
+CONFIG += console
3
+CONFIG -= app_bundle
4
+CONFIG -= qt
5
+
6
+SOURCES += main.cpp
7
+

+ 130
- 0
UnitTests/main.cpp Datei anzeigen

@@ -0,0 +1,130 @@
1
+#include <iostream>
2
+#include <cassert>
3
+
4
+using namespace std;
5
+
6
+//
7
+// Function fact(n): Given a positive number n will return its factorial.
8
+//
9
+unsigned int fact(unsigned int n) {
10
+
11
+    if (n <= 0) return 0;
12
+
13
+    int result = 1;
14
+
15
+    for (int i = 1; i < n; i++)
16
+        result = result * i;
17
+
18
+    return result;
19
+}
20
+
21
+
22
+// 
23
+// Function isALetter(c):
24
+// Given a character c will return true if it is a letter,
25
+// otherwise returns false.
26
+//
27
+
28
+bool isALetter(char c) {
29
+    return ( c >= 'A' && c <= 'z');
30
+}
31
+
32
+//
33
+// Function isValidTime(n:
34
+// Given a time in military format, e.g. 1147, determines if it is valid. 
35
+// Returns true if valid, false otherwise.
36
+//
37
+
38
+bool isValidTime(unsigned int n) {
39
+    return ( n >= 0 && n <= 2359 );
40
+}
41
+
42
+
43
+//
44
+// Function gcd(a,b):
45
+// Given two positive integeres, determines their greatest common divisor 
46
+// and returns it.
47
+//
48
+
49
+int gcd ( int a, int b ) {
50
+    int c;
51
+
52
+    while ( a > 1 ) {
53
+        c = a;
54
+        a = b % a;
55
+        b = c;
56
+    }
57
+    return b;
58
+}
59
+
60
+
61
+//
62
+// Function test_fact():
63
+// This function is provided as an example unit test for the fact() function. 
64
+//
65
+
66
+void test_fact() {
67
+    assert( fact(1) == 1 );
68
+    assert( fact(2) == 2);
69
+    assert( fact(4) == 24);
70
+    cout << "Function fact() passed all the tests!!" << endl;
71
+}
72
+
73
+//
74
+// EXERCISE 3
75
+//
76
+
77
+
78
+//
79
+// Function test_isALetter():
80
+// This function is provided as an example unit test for the isALetter() function.
81
+//
82
+
83
+void test_isALetter() {
84
+    assert( isALetter('a') );
85
+    assert( isALetter('Z'));
86
+    assert( isALetter('2')==0);
87
+    assert( isALetter('$')==0);
88
+    assert( isALetter('^')==0);
89
+    cout << "Function isALetter() passed all the tests!!" << endl;
90
+}
91
+
92
+//
93
+// Function test_isValidTime():
94
+// This function is provided as an example unit test for the isValidTime() function.
95
+//
96
+
97
+void test_isValidTime() {
98
+    assert( isValidTime(0002) );
99
+    assert( isValidTime(1234) );
100
+    assert( isValidTime(4800)==0 );
101
+    assert( isValidTime(1278)==0 );
102
+    cout << "Function isValidTime() passed all the tests!!" << endl;
103
+}
104
+
105
+//
106
+// Function test_gcd():
107
+// This function is provided as an example unit test for the gcd() function.
108
+//
109
+
110
+void test_gcd() {
111
+    assert( gcd(1,1)==1 );
112
+    assert( gcd(2,2)==2 );
113
+    assert( gcd(3,2)==1 );
114
+    assert( gcd(12,9)==3 );
115
+    assert( gcd(12,6)==6 );
116
+    cout << "Function gcd() passed all the tests!!" << endl;
117
+}
118
+
119
+
120
+
121
+int main()
122
+{
123
+    cout << "Go ahead and test!\n";
124
+    test_fact();
125
+ // test_gcd();
126
+ // test_isALetter();
127
+ // test_isValidTime();
128
+    
129
+    return 0;
130
+}

+ 265
- 42
functions.cpp Datei anzeigen

@@ -111,32 +111,59 @@ void mySortDelta(QString &a, QString &b, QString &c) {
111 111
 }
112 112
 
113 113
 
114
+//========================================================
115
+// Functions for the dice roller
116
+//========================================================
117
+
118
+//This is the correct dice roller
119
+void MainWindow::diceAlpha(){
120
+    int total = diceFinal01 + diceFinal02 + 2;
121
+    line[0]->setText(QString::number(total));
122
+}
114 123
 
124
+//This version sums the first dice twice
125
+void MainWindow::diceBeta(){
126
+    int total = diceFinal01 + diceFinal01 + 2;
127
+    line[0]->setText(QString::number(total));
128
+}
129
+
130
+//This one substracts the second dice to the first one
131
+void MainWindow::diceGamma(){
132
+    int total = diceFinal01 - diceFinal02;
133
+    line[0]->setText(QString::number(total));
134
+}
135
+
136
+//This one takes the number 6 as a 12
137
+void MainWindow::diceDelta(){
138
+    int total = diceFinal01 + diceFinal02;
139
+    line[0]->setText(QString::number(total));
140
+}
115 141
 
116 142
 // =========================================================
117 143
 // Rock Paper Scissor Functions
118 144
 // =========================================================
119 145
 
120 146
 
147
+
121 148
 int RPSAlpha(char p1, char p2) {
122 149
     p1 = toupper(p1);
123 150
     p2 = toupper(p2);
124 151
     if ( p1 == 'P' ) {
125
-        if ( p2 == 'P' )    return TIE;
126
-        else if (p2 == 'R') return P1_WON;
127
-        else                return P2_WON;
152
+        if ( p2 == 'P' )    return 0;
153
+        else if (p2 == 'R') return 1;
154
+        else                return 2;
128 155
     }
129 156
 
130 157
     else if (p1 == 'R') {
131
-        if ( p2 == 'R' )    return TIE;
132
-        else if (p2 == 'S') return P1_WON;
133
-        else                return P2_WON;
158
+        if ( p2 == 'R' )    return 0;
159
+        else if (p2 == 'S') return 1;
160
+        else                return 2;
134 161
     }
135 162
 
136 163
     else {
137
-        if ( p2 == 'S' )    return TIE;
138
-        else if (p2 == 'P') return P1_WON;
139
-        else                return P2_WON;
164
+        if ( p2 == 'S' )    return 0;
165
+        else if (p2 == 'P') return 1;
166
+        else                return 2;
140 167
     }
141 168
 }
142 169
 
@@ -145,20 +172,20 @@ int RPSBeta(char p1, char p2) {
145 172
     p1 = toupper(p1);
146 173
     p2 = toupper(p2);
147 174
     if ( p1 == 'P' ) {
148
-        if ( p2 == 'S' )    return TIE;
149
-        else if (p2 == 'R') return P1_WON;
150
-        else                return P2_WON;
175
+        if ( p2 == 'S' )    return 0;
176
+        else if (p2 == 'R') return 1;
177
+        else                return 2;
151 178
     }
152 179
     else if (p1 == 'R') {
153
-        if ( p2 == 'S' )    return TIE;
154
-        else if (p2 == 'P') return P1_WON;
155
-        else                return P2_WON;
180
+        if ( p2 == 'S' )    return 0;
181
+        else if (p2 == 'P') return 1;
182
+        else                return 2;
156 183
     }
157 184
 
158 185
     else {
159
-        if ( p2 == 'S' )    return TIE;
160
-        else if (p2 == 'R') return P1_WON;
161
-        else                return P2_WON;
186
+        if ( p2 == 'S' )    return 0;
187
+        else if (p2 == 'R') return 1;
188
+        else                return 2;
162 189
     }
163 190
 }
164 191
 
@@ -168,40 +195,41 @@ int RPSGamma(char p1, char p2) {
168 195
     p1 = toupper(p1);
169 196
     p2 = toupper(p2);
170 197
     if ( p1 == 'P' ) {
171
-        if ( p2 == 'P' )    return TIE;
172
-        else if (p2 == 'S') return P1_WON;
173
-        else                return P2_WON;
198
+        if ( p2 == 'P' )    return 0;
199
+        else if (p2 == 'S') return 1;
200
+        else                return 2;
174 201
     }
175 202
     else if (p1 == 'R') {
176
-        if ( p2 == 'R' )    return TIE;
177
-        else if (p2 == 'P') return P1_WON;
178
-        else                return P2_WON;
203
+        if ( p2 == 'R' )    return 0;
204
+        else if (p2 == 'P') return 1;
205
+        else                return 2;
179 206
     }
180 207
     else {
181
-        if ( p2 == 'P' )    return TIE;
182
-        else if (p2 == 'S') return P1_WON;
183
-        else                return P2_WON;
208
+        if ( p2 == 'P' )    return 0;
209
+        else if (p2 == 'S') return 1;
210
+        else                return 2;
184 211
     }
185 212
 }
186 213
 
187 214
 
215
+
188 216
 int RPSDelta(char p1, char p2) {
189 217
     p1 = toupper(p1);
190 218
     p2 = toupper(p2);
191 219
     if ( p1 == 'P' ) {
192
-        if ( p2 == 'P' )    return TIE;
193
-        else if (p2 == 'S') return P1_WON;
194
-        else                return P2_WON;
220
+        if ( p2 == 'P' )    return 0;
221
+        else if (p2 == 'S') return 1;
222
+        else                return 2;
195 223
     }
196 224
     else if (p1 == 'R') {
197
-        if ( p2 == 'R' )    return TIE;
198
-        else if (p2 == 'P') return P1_WON;
199
-        else                return P2_WON;
225
+        if ( p2 == 'R' )    return 0;
226
+        else if (p2 == 'P') return 1;
227
+        else                return 2;
200 228
     }
201 229
     else {
202
-        if ( p2 == 'P' )    return TIE;
203
-        else if (p2 == 'S') return P1_WON;
204
-        else                return P2_WON;
230
+        if ( p2 == 'P' )    return 0;
231
+        else if (p2 == 'S') return 1;
232
+        else                return 2;
205 233
     }
206 234
 }
207 235
 
@@ -213,6 +241,11 @@ int RPSDelta(char p1, char p2) {
213 241
 
214 242
 QMap<int,QString> M;
215 243
 
244
+///
245
+/// \brief initCheckWMaps: initialize the values in the dictionary that is used throughout
246
+///                        the check functions.
247
+///
248
+
216 249
 void initCheckWMaps() {
217 250
 
218 251
     M[1] = "one";       M[2] = "two";       M[3]  = "three";      M[4] = "four";
@@ -226,6 +259,13 @@ void initCheckWMaps() {
226 259
 }
227 260
 
228 261
 
262
+///
263
+/// \brief validateCheckQty: determines is entered text is a valid number in [0,999999999]
264
+/// \param st text entered by the user
265
+/// \param qty text converted to integer
266
+/// \return true if the entered text is valid
267
+///
268
+
229 269
 bool validateCheckQty(QString st, unsigned int &qty) {
230 270
     int i = 0;
231 271
     for (i = 0; i < st.length() ; i++) {
@@ -238,9 +278,13 @@ bool validateCheckQty(QString st, unsigned int &qty) {
238 278
     return true;
239 279
 }
240 280
 
281
+///
282
+/// \brief wordForNumber: Given a number n in [0,999] returns the word equivalent
283
+/// \param n: the number
284
+/// \return a Qstring containing the number in words
285
+///
241 286
 
242
-
243
-QString wordForNumber(unsigned int n) {
287
+QString wordForNumber(int n) {
244 288
     QString st;
245 289
 
246 290
     int tens = n % 100;
@@ -261,8 +305,13 @@ QString wordForNumber(unsigned int n) {
261 305
 }
262 306
 
263 307
 
308
+///
309
+/// \brief checkWAlpha: One of the functions to convert a number in [0,999999999] to words
310
+/// \param n: the number
311
+/// \return a Qstring containing the number in words
312
+///
264 313
 
265
-QString checkWAlpha(unsigned int n) {
314
+QString checkWAlpha(int n) {
266 315
     QString st;
267 316
 
268 317
     // the cents
@@ -279,8 +328,13 @@ QString checkWAlpha(unsigned int n) {
279 328
     return st;
280 329
 }
281 330
 
331
+///
332
+/// \brief checkWBeta: One of the functions to convert a number in [0,999999999] to words
333
+/// \param n: the number
334
+/// \return a Qstring containing the number in words
335
+///
282 336
 
283
-QString checkWBeta(unsigned int n) {
337
+QString checkWBeta(int n) {
284 338
     QString st;
285 339
 
286 340
     st = wordForNumber(n % 1000);
@@ -292,8 +346,13 @@ QString checkWBeta(unsigned int n) {
292 346
     return st;
293 347
 }
294 348
 
349
+///
350
+/// \brief checkWGamma: One of the functions to convert a number in [0,999999999] to words
351
+/// \param n: the number
352
+/// \return a Qstring containing the number in words
353
+///
295 354
 
296
-QString checkWGamma(unsigned int n) {
355
+QString checkWGamma(int n) {
297 356
     QString st;
298 357
 
299 358
     st = wordForNumber(n % 10);
@@ -305,9 +364,14 @@ QString checkWGamma(unsigned int n) {
305 364
     return st;
306 365
 }
307 366
 
367
+///
368
+/// \brief checkWDelta: One of the functions to convert a number in [0,999999999] to words
369
+/// \param n: the number
370
+/// \return a Qstring containing the number in words
371
+///
308 372
 
309 373
 
310
-QString checkWDelta(unsigned int n) {
374
+QString checkWDelta(int n) {
311 375
     QString st;
312 376
 
313 377
     n /= 10;
@@ -342,6 +406,7 @@ bool validZuluTime(const QString &time, const QString &zone, int &hours, int &mi
342 406
     return true;
343 407
 }
344 408
 
409
+//This is the correct one
345 410
 
346 411
 QString zuluAlpha(int hours, int minutes, char zone) {
347 412
     int diff = 0;
@@ -399,3 +464,161 @@ QString zuluDelta(int hours, int minutes, char zone) {
399 464
 
400 465
     return QString::number(hours)  + QString::number(minutes);
401 466
 }
467
+
468
+
469
+
470
+// =========================================================
471
+// APFT Functions
472
+// =========================================================
473
+
474
+
475
+//This it the correct one
476
+
477
+void MainWindow::APFTAlpha(){
478
+    //For each one of these variables we apply the formula that they use
479
+    //to set the points
480
+    double sit_ups = qFloor(line[0]->text().toDouble() * 1.6 - 24.8);
481
+
482
+    double push_ups = qFloor(line[1]->text().toInt() * 1.42);
483
+
484
+    double running_time = qFloor((line[2]->text().left(2).append('.' + line[2]->text().right(2))).toDouble());
485
+    double two_mile_run = qFloor((820 / 3) - ((40 * running_time) / 3));
486
+
487
+    //Since the maximum of points that one can obtain
488
+    //on each excercise type is 100, we restrict it
489
+    if (sit_ups > 100){
490
+        sit_ups = 100;
491
+    }
492
+    else if (sit_ups < 0){
493
+        sit_ups = 0;
494
+    }
495
+    if (push_ups > 100){
496
+        push_ups = 100;
497
+    }
498
+    else if (push_ups < 0){
499
+        push_ups = 0;
500
+    }
501
+    if (two_mile_run > 100){
502
+        two_mile_run = 100;
503
+    }
504
+    else if (two_mile_run < 0){
505
+        two_mile_run = 0;
506
+    }
507
+
508
+    //Finally we set the outputs.
509
+    line[3]->setText(QString::number(sit_ups));
510
+    line[4]->setText(QString::number(push_ups));
511
+    line[5]->setText(QString::number(two_mile_run));
512
+    line[6]->setText(QString::number(push_ups + sit_ups + two_mile_run));
513
+    if (push_ups >= 60 && sit_ups >= 60 && two_mile_run >= 60){
514
+        label[7]->setText("PASS");
515
+    }
516
+    else{
517
+        label[7]->setText("FAIL");
518
+    }
519
+}
520
+
521
+//This one do not check if the number is greater than 100
522
+
523
+void MainWindow::APFTBeta(){
524
+    double sit_ups = qFloor(line[0]->text().toDouble() * 1.6 - 24.8);
525
+
526
+    double push_ups = qFloor(line[1]->text().toInt() * 1.42);
527
+
528
+    double running_time = qFloor((line[2]->text().left(2).append('.' + line[2]->text().right(2))).toDouble());
529
+    double two_mile_run = qFloor((820 / 3) - ((40 * running_time) / 3));
530
+
531
+    line[3]->setText(QString::number(sit_ups));
532
+    line[4]->setText(QString::number(push_ups));
533
+    line[5]->setText(QString::number(two_mile_run));
534
+    line[6]->setText(QString::number(push_ups + sit_ups + two_mile_run));
535
+    if (push_ups >= 60 && sit_ups >= 60 && two_mile_run >= 60){
536
+        line[7]->setText("PASS");
537
+    }
538
+    else{
539
+        line[7]->setText("FAIL");
540
+    }
541
+}
542
+
543
+//This one switch the results
544
+
545
+void MainWindow::APFTGamma(){
546
+    double sit_ups = qFloor(line[0]->text().toDouble() * 1.6 - 24.8);
547
+    double push_ups = qFloor(line[1]->text().toInt() * 1.42);
548
+    double running_time = qFloor((line[2]->text().left(2).append('.' + line[2]->text().right(2))).toDouble());
549
+    double two_mile_run = qFloor((820 / 3) - ((40 * running_time) / 3));
550
+
551
+    if (sit_ups > 100){
552
+        sit_ups = 100;
553
+    }
554
+    else if (sit_ups < 0){
555
+        sit_ups = 0;
556
+    }
557
+    if (push_ups > 100){
558
+        push_ups = 100;
559
+    }
560
+    else if (push_ups < 0){
561
+        push_ups = 0;
562
+    }
563
+    if (two_mile_run > 100){
564
+        two_mile_run = 100;
565
+    }
566
+    else if (two_mile_run < 0){
567
+        two_mile_run = 0;
568
+    }
569
+
570
+    line[5]->setText(QString::number(sit_ups));
571
+    line[3]->setText(QString::number(push_ups));
572
+    line[4]->setText(QString::number(two_mile_run));
573
+    line[6]->setText(QString::number(push_ups + sit_ups + two_mile_run));
574
+    if (push_ups >= 60 && sit_ups >= 60 && two_mile_run >= 60){
575
+        line[7]->setText("PASS");
576
+    }
577
+    else{
578
+        line[7]->setText("FAIL");
579
+    }
580
+}
581
+
582
+//This one do not sums the points but the quantities of each excercise
583
+
584
+void MainWindow::APFTDelta(){
585
+    double sit_ups = qFloor(line[0]->text().toDouble() * 1.6 - 24.8);
586
+    double push_ups = qFloor(line[1]->text().toInt() * 1.42);
587
+    double running_time = qFloor((line[2]->text().left(2).append('.'
588
+                                   + line[2]->text().right(2))).toDouble());
589
+    double two_mile_run = qFloor((820 / 3) - ((40 * running_time) / 3));
590
+
591
+    if (sit_ups > 100){
592
+        sit_ups = 100;
593
+    }
594
+    else if (sit_ups < 0){
595
+        sit_ups = 0;
596
+    }
597
+    if (push_ups > 100){
598
+        push_ups = 100;
599
+    }
600
+    else if (push_ups < 0){
601
+        push_ups = 0;
602
+    }
603
+    if (two_mile_run > 100){
604
+        two_mile_run = 100;
605
+    }
606
+    else if (two_mile_run < 0){
607
+        two_mile_run = 0;
608
+    }
609
+
610
+    int sumaTo = line[0]->text().toInt() + line[1]->text().toInt() + running_time;
611
+    line[3]->setText(QString::number(sit_ups));
612
+    line[4]->setText(QString::number(push_ups));
613
+    line[5]->setText(QString::number(two_mile_run));
614
+    line[6]->setText(QString::number(sumaTo));
615
+    if (push_ups >= 60 && sit_ups >= 60 && two_mile_run >= 60){
616
+        line[7]->setText("PASS");
617
+    }
618
+    else{
619
+        line[7]->setText("FAIL");
620
+    }
621
+}
622
+
623
+
624
+

+ 4
- 292
functions.h Datei anzeigen

@@ -4,316 +4,28 @@
4 4
 #include <string>
5 5
 using namespace std;
6 6
 
7
-
8
-/// \fn validateSorts
9
-/// \~English
10
-/// \brief Function to validate that sort is invoked with non-empty strings
11
-/// \param a first QSring
12
-/// \param b second Qstring
13
-/// \param c third QString
14
-/// \return true if non of the QStrings are empty
15
-/// \~Spanish
16
-/// \brief Valida que los QStrings que se van a ordenar no estén vacios.
17
-/// \param a primer QSring
18
-/// \param b segundo Qstring
19
-/// \param c tercer QString
20
-/// \return true si ninguno de los QString está vacio
21 7
 bool validateSorts(const QString &a, const QString &b, const QString &c);
22
-
23
-/// \fn mySortAlpha
24
-/// \~English
25
-/// \brief A function to sort the QStrings. Returns the order 
26
-/// strings through the parameters (a is smallest, c is largest).
27
-/// \param a reference to first QSring
28
-/// \param b reference to second Qstring
29
-/// \param c reference to third QString
30
-/// \~Spanish
31
-/// \brief Función para ordenar QStrings. Devuelve los QStrings
32
-/// ordenados a través de los parámetros (a para el menor, c para el mayor).
33
-/// \param a referencia al primer QSring
34
-/// \param b referencia al segundo Qstring
35
-/// \param c referencia al tercer QString
36 8
 void mySortAlpha(QString &a, QString &b, QString &c);
37
-
38
-/// \fn mySortBeta
39
-/// \~English
40
-/// \brief A function to sort the QStrings. Returns the order 
41
-/// strings through the parameters (a is smallest, c is largest).
42
-/// \param a reference to first QSring
43
-/// \param b reference to second Qstring
44
-/// \param c reference to third QString
45
-/// \~Spanish
46
-/// \brief Función para ordenar QStrings. Devuelve los QStrings
47
-/// ordenados a través de los parámetros (a para el menor, c para el mayor).
48
-/// \param a referencia al primer QSring
49
-/// \param b referencia al segundo Qstring
50
-/// \param c referencia al tercer QString
51 9
 void mySortBeta(QString &a, QString &b, QString &c);
52
-
53
-/// \fn mySortGamma
54
-/// \~English
55
-/// \brief A function to sort the QStrings. Returns the order 
56
-/// strings through the parameters (a is smallest, c is largest).
57
-/// \param a reference to first QSring
58
-/// \param b reference to second Qstring
59
-/// \param c reference to third QString
60
-/// \~Spanish
61
-/// \brief Función para ordenar QStrings. Devuelve los QStrings
62
-/// ordenados a través de los parámetros (a para el menor, c para el mayor).
63
-/// \param a referencia al primer QSring
64
-/// \param b referencia al segundo Qstring
65
-/// \param c referencia al tercer QString
66 10
 void mySortGamma(QString &a, QString &b, QString &c);
67
-
68
-/// \fn mySortDelta
69
-/// \~English
70
-/// \brief First function to sort the QStrings. Returns the order 
71
-/// strings through the parameters (a is smallest, c is largest).
72
-/// \param a reference to first QSring
73
-/// \param b reference to second Qstring
74
-/// \param c reference to third QString
75
-/// \~Spanish
76
-/// \brief Función para ordenar QStrings. Devuelve los QStrings
77
-/// ordenados a través de los parámetros (a para el menor, c para el mayor).
78
-/// \param a referencia al primer QSring
79
-/// \param b referencia al segundo Qstring
80
-/// \param c referencia al tercer QString
81 11
 void mySortDelta(QString &a, QString &b, QString &c);
82 12
 
83
-
84
-/// \fn validZuluTime
85
-/// \~English
86
-/// \brief Function to validate the arguments that will be passed to the
87
-///  Zulu functions.  Returns the integer hour and minutes through last two parameters.
88
-/// \param time QString that contains the time in military format.
89
-/// \param zone  QString that specifies military zone.
90
-/// \param hours hours, extracted from the time parameter
91
-/// \param minutes minutes, extracted from the time parameter
92
-/// \return true if the time and zone are valid. 
93
-/// \~Spanish
94
-/// \brief Función para validar los argumentos que serán pasados a
95
-/// funciones Zulu.  Devuelve (como enteros) la hora y minutos a través de los 
96
-/// últimos dos parámetros.
97
-/// \param time QString que contiene la hora en formato militar, e.g. "15:22"
98
-/// \param zone  QString que contiene zona militar.
99
-/// \param hours horas, extraida del argumento pasado a time.
100
-/// \param minutes minutos, extraidos del argumento pasado a time.
101
-/// \return true si la hora (time) y la zona son válidas. 
102 13
 bool validZuluTime(const QString &time, const QString &zone, int &hours, int &minutes);
103
-
104
-
105
-/// \fn zuluAlpha
106
-/// \~English
107
-/// \brief Given the hour, minutes and military zone returns the Zulu time (as a QString)
108
-/// \param hours 
109
-/// \param minutes 
110
-/// \param zone 
111
-/// \return a QString of the Zulu time, in military time format
112
-/// \~Spanish
113
-/// \brief Dado la hora, minutos y zona militar devuelve el tiempo Zulu (como QString)
114
-/// \param hours 
115
-/// \param minutes 
116
-/// \param zone 
117
-/// \return un QString del tiempo Zulu, en formato de hora militar.
118 14
 QString zuluAlpha(int hours, int minutes, char zone);
119
-
120
-
121
-/// \fn zuluBeta
122
-/// \~English
123
-/// \brief Given the hour, minutes and military zone returns the Zulu time (as a QString)
124
-/// \param hours 
125
-/// \param minutes 
126
-/// \param zone 
127
-/// \return a QString of the Zulu time, in military time format
128
-/// \~Spanish
129
-/// \brief Dado la hora, minutos y zona militar devuelve el tiempo Zulu (como QString)
130
-/// \param hours 
131
-/// \param minutes 
132
-/// \param zone 
133
-/// \return un QString del tiempo Zulu, en formato de hora militar.
134 15
 QString zuluBeta(int hours, int minutes, char zone);
135
-
136
-
137
-/// \fn zuluGamma
138
-/// \~English
139
-/// \brief Given the hour, minutes and military zone returns the Zulu time (as a QString)
140
-/// \param hours 
141
-/// \param minutes 
142
-/// \param zone 
143
-/// \return a QString of the Zulu time, in military time format
144
-/// \~Spanish
145
-/// \brief Dado la hora, minutos y zona militar devuelve el tiempo Zulu (como QString)
146
-/// \param hours 
147
-/// \param minutes 
148
-/// \param zone 
149
-/// \return un QString del tiempo Zulu, en formato de hora militar.
150 16
 QString zuluGamma(int hours, int minutes, char zone);
151
-
152
-
153
-/// \fn zuluDelta
154
-/// \~English
155
-/// \brief Given the hour, minutes and military zone returns the Zulu time (as a QString)
156
-/// \param hours 
157
-/// \param minutes 
158
-/// \param zone 
159
-/// \return a QString of the Zulu time, in military time format
160
-/// \~Spanish
161
-/// \brief Dado la hora, minutos y zona militar devuelve el tiempo Zulu (como QString)
162
-/// \param hours 
163
-/// \param minutes 
164
-/// \param zone 
165
-/// \return un QString del tiempo Zulu, en formato de hora militar.
166 17
 QString zuluDelta(int hours, int minutes, char zone);
167 18
 
168
-
169
-// Constants for the rock, paper, scisor functions.
170
-const int TIE = 0;
171
-const int P1_WON = 1;
172
-const int P2_WON = 2;
173
-
174
-
175
-/// \fn RPSAlpha
176
-/// \~English
177
-/// \brief Given play by the first and second players, returns who won the rock, paper
178
-/// scisors match.
179
-/// \param p1 play by the first player, as represented by char 'R', 'P' or 'S' 
180
-/// \param p2 play by the first player, as represented by char 'R', 'P' or 'S'  
181
-/// \return a 0 if there was a tie, 1 if the first player won, 2 if the second player won.
182
-/// \~Spanish
183
-/// \brief Dado la jugada del jugador 1 y 2, devuelve quien ganó el juego de piedra, 
184
-/// papel y tijera ((R)ock, (P)aper, (S)cisors)
185
-/// \param p1 jugada del primer jugador, representada por un caracter ('R','P','S') 
186
-/// \param p1 jugada del segundo jugador, representada por un caracter ('R','P','S')
187
-/// \return a 0 si hubo empate, 1 si ganó el primer jugador, 2 si ganó el segundo.
188 19
 int RPSAlpha(char p1, char p2);
189
-
190
-/// \fn RPSBeta
191
-/// \~English
192
-/// \brief Given play by the first and second players, returns who won the rock, paper
193
-/// scisors match.
194
-/// \param p1 play by the first player, as represented by char 'R', 'P' or 'S' 
195
-/// \param p2 play by the first player, as represented by char 'R', 'P' or 'S'  
196
-/// \return a 0 if there was a tie, 1 if the first player won, 2 if the second player won.
197
-/// \~Spanish
198
-/// \brief Dado la jugada del jugador 1 y 2, devuelve quien ganó el juego de piedra, 
199
-/// papel y tijera ((R)ock, (P)aper, (S)cisors)
200
-/// \param p1 jugada del primer jugador, representada por un caracter ('R','P','S') 
201
-/// \param p1 jugada del segundo jugador, representada por un caracter ('R','P','S')
202
-/// \return a 0 si hubo empate, 1 si ganó el primer jugador, 2 si ganó el segundo.
203 20
 int RPSBeta(char p1, char p2);
204
-
205
-/// \fn RPSGamma
206
-/// \~English
207
-/// \brief Given play by the first and second players, returns who won the rock, paper
208
-/// scisors match.
209
-/// \param p1 play by the first player, as represented by char 'R', 'P' or 'S' 
210
-/// \param p2 play by the first player, as represented by char 'R', 'P' or 'S'  
211
-/// \return a 0 if there was a tie, 1 if the first player won, 2 if the second player won.
212
-/// \~Spanish
213
-/// \brief Dado la jugada del jugador 1 y 2, devuelve quien ganó el juego de piedra, 
214
-/// papel y tijera ((R)ock, (P)aper, (S)cisors)
215
-/// \param p1 jugada del primer jugador, representada por un caracter ('R','P','S') 
216
-/// \param p1 jugada del segundo jugador, representada por un caracter ('R','P','S')
217
-/// \return a 0 si hubo empate, 1 si ganó el primer jugador, 2 si ganó el segundo.
218 21
 int RPSGamma(char p1, char p2);
219
-
220
-/// \fn RPSDelta
221
-/// \~English
222
-/// \brief Given play by the first and second players, returns who won the rock, paper
223
-/// scisors match.
224
-/// \param p1 play by the first player, as represented by char 'R', 'P' or 'S' 
225
-/// \param p2 play by the first player, as represented by char 'R', 'P' or 'S'  
226
-/// \return a 0 if there was a tie, 1 if the first player won, 2 if the second player won.
227
-/// \~Spanish
228
-/// \brief Dado la jugada del jugador 1 y 2, devuelve quien ganó el juego de piedra, 
229
-/// papel y tijera ((R)ock, (P)aper, (S)cisors)
230
-/// \param p1 jugada del primer jugador, representada por un caracter ('R','P','S') 
231
-/// \param p1 jugada del segundo jugador, representada por un caracter ('R','P','S')
232
-/// \param zone 
233
-/// \return a 0 si hubo empate, 1 si ganó el primer jugador, 2 si ganó el segundo.
234 22
 int RPSDelta(char p1, char p2);
235 23
 
236
-
237
-/// \fn initCheckWMaps
238
-/// \~English
239
-/// \brief Initialize the values in the dictionary (M) that is used throughout
240
-/// the check functions.
241
-/// \~Spanish
242
-/// \brief Inicializa los valores del diccionario que se utiliza a través del 
243
-/// las funciones 'check' 
244 24
 void initCheckWMaps();
245
-
246
-
247
-
248
-/// \fn validateCheckQty
249
-/// \~English
250
-/// \brief Given a QString determines its numerical value and if the 
251
-/// the value is in the range [0,999999999]
252
-/// \param st a QString with a numeric value, e.g. "4520"
253
-/// \param qty unsigned integer to return the numeric value, e.g. 4520
254
-/// \return true if the QString was converted to an integer and is in the valid range
255
-/// \~Spanish
256
-/// \brief Dado un string determina su valor numérico y si el valor está en el 
257
-/// rango [0,999999999]
258
-/// \param st un QString con un valor numérico, e.g. "4520"
259
-/// \param qty entero sin signo para devolver el valor numérico, e.g. 4520
260
-/// \return true si el QString se pudo convertir a entero y está en el rango
261 25
 bool validateCheckQty(QString st, unsigned int &qty);
262
-
263
-
264
-/// \fn wordForNumber
265
-/// \~English
266
-/// \brief Given a number n in [0,999] returns the word equivalent
267
-/// \param n the unsigned integer, e.g. 34
268
-/// \return a QString containing the number in words, e.g. "thirty four"
269
-/// \~Spanish
270
-/// \brief Dado un número entero en el rango [0,999] devuelve su representación en palabras
271
-/// \param n el entero sin signo, e.g. 34
272
-/// \return un QString que contiene el valor en palabras, e.g. "thirty four"
273
-QString wordForNumber(unsigned int n);
274
-
275
-/// \fn checkWAlpha
276
-/// \~English
277
-/// \brief Given a unsigned integer returns its value as a string of words (in English)
278
-/// \param n the unsigned integer, e.g. 42
279
-/// \return QString containing the value (in words), e.g. "fourty two"
280
-/// \~Spanish
281
-/// \brief Dado un entero sin signo devuelve su valor como un string de palabras (in English)
282
-/// \param n el entero sin signo, e.g. 42
283
-/// \return QString que contien el valor en palabras, e.g. "fourty two"
284
-QString checkWAlpha(unsigned int n);
285
-
286
-/// \fn checkWBeta
287
-/// \~English
288
-/// \brief Given a unsigned integer returns its value as a string of words (in English)
289
-/// \param n the unsigned integer, e.g. 42
290
-/// \return QString containing the value (in words), e.g. "fourty two"
291
-/// \~Spanish
292
-/// \brief Dado un entero sin signo devuelve su valor como un string de palabras (in English)
293
-/// \param n el entero sin signo, e.g. 42
294
-/// \return QString que contien el valor en palabras, e.g. "fourty two"
295
-QString checkWBeta(unsigned int n);
296
-
297
-/// \fn checkWGamma
298
-/// \~English
299
-/// \brief Given a unsigned integer returns its value as a string of words (in English)
300
-/// \param n the unsigned integer, e.g. 42
301
-/// \return QString containing the value (in words), e.g. "fourty two"
302
-/// \~Spanish
303
-/// \brief Dado un entero sin signo devuelve su valor como un string de palabras (in English)
304
-/// \param n el entero sin signo, e.g. 42
305
-/// \return QString que contien el valor en palabras, e.g. "fourty two"
306
-QString checkWGamma(unsigned int n);
307
-
308
-/// \fn checkWDelta
309
-/// \~English
310
-/// \brief Given a unsigned integer returns its value as a string of words (in English)
311
-/// \param n the unsigned integer, e.g. 42
312
-/// \return QString containing the value (in words), e.g. "fourty two"
313
-/// \~Spanish
314
-/// \brief Dado un entero sin signo devuelve su valor como un string de palabras (in English)
315
-/// \param n el entero sin signo, e.g. 42
316
-/// \return QString que contien el valor en palabras, e.g. "fourty two"
317
-QString checkWDelta(unsigned int n);
26
+QString checkWAlpha(int n);
27
+QString checkWBeta(int n);
28
+QString checkWGamma(int n);
29
+QString checkWDelta(int n);
318 30
 
319 31
 #endif // FUNCTIONS_H

+ 0
- 1
images.qrc Datei anzeigen

@@ -6,6 +6,5 @@
6 6
         <file>resources/d4.png</file>
7 7
         <file>resources/d5.png</file>
8 8
         <file>resources/d6.png</file>
9
-        <file>resources/logo.png</file>
10 9
     </qresource>
11 10
 </RCC>

BIN
imagesTesting.zip Datei anzeigen


+ 48
- 1
main.cpp Datei anzeigen

@@ -6,17 +6,64 @@
6 6
 #include <cassert>
7 7
 #include <QDebug>
8 8
 
9
+void testSort() {
10
+    QString a = "AAA" , b = "BBB" , c = "CCC";
11
+    mySortBeta(a,b,c);
12
+    assert( a < b && b < c);
9 13
 
14
+    a = "AAA", b = "CCC", c = "BBB";
15
+    mySortBeta(a,b,c);
16
+    assert( a < b && b < c);
17
+
18
+    a = "BBB", b = "AAA", c = "CCC";
19
+    mySortBeta(a,b,c);
20
+    assert( a < b && b < c);
21
+
22
+    a = "BBB", b = "CCC", c = "AAA";
23
+    mySortBeta(a,b,c);
24
+    assert( a < b && b < c);
25
+
26
+    a = "CCC", b = "AAA", c = "BBB";
27
+    mySortBeta(a,b,c);
28
+    //qDebug() << a << b << c;
29
+    assert( a < b && b < c);
30
+
31
+    a = "CCC", b = "BBB", c = "AAA";
32
+    mySortBeta(a,b,c);
33
+    assert( a < b && b < c);
34
+
35
+    qDebug() << "Passed Test for Sort!!!!";
36
+}
37
+
38
+void testCheck() {
39
+
40
+    assert( checkWAlpha(91) == QString("ninety one"));
41
+    assert( checkWAlpha(891) == QString("eight hundred ninety one"));
42
+    assert( checkWAlpha(100) == QString("one hundred"));
43
+    assert( checkWAlpha(59123) == QString("fifty nine thousand one hundred twenty three"));
44
+    assert( checkWAlpha(100001) == QString("one hundred thousand one"));
45
+    assert( checkWAlpha(100000) == QString("one hundred thousand"));
46
+    assert( checkWAlpha(100000000) == QString("one hundred million"));
47
+    qDebug() << "Passed Test for Check Word!!!!";
48
+}
10 49
 
11 50
 int main(int argc, char *argv[])
12 51
 {
52
+//    testSort();
53
+    initCheckWMaps(); /*** DONT FORGET ***/
54
+
55
+//    testCheck();
56
+//    qDebug() << checkWAlpha(91);
57
+//    qDebug() << checkWAlpha(891);
58
+//    qDebug() << checkWAlpha(801);
13 59
 
14
-    initCheckWMaps(); 
15 60
 
16 61
     srand(time(NULL));
17 62
     QApplication a(argc, argv);
18 63
     MainWindow w;
19 64
     w.show();
20 65
 
66
+
67
+
21 68
     return a.exec();
22 69
 }

+ 278
- 57
mainwindow.cpp Datei anzeigen

@@ -6,7 +6,6 @@
6 6
 #include "secondwindow.cpp"
7 7
 
8 8
 #include <QDebug>
9
-#include <QTimer>
10 9
 #include <QtCore/qmath.h>
11 10
 #include <QMessageBox>
12 11
 #include "functions.h"
@@ -42,7 +41,7 @@ MainWindow::MainWindow(QWidget *parent) :
42 41
 
43 42
     // We need to know whenever the second window is closed to show the
44 43
     // main window, or to hide when the second one is showed
45
-    connect(window, SIGNAL(closeIt(bool)), this, SLOT(showMW(bool)));
44
+    connect(window, SIGNAL(cerrado(bool)), this, SLOT(mostrar(bool)));
46 45
 
47 46
     if(!dice1.load(":/images/resources/d1.png") || !dice2.load(":/images/resources/d1.png")){
48 47
         qDebug() << "Error1 Loading image";
@@ -56,8 +55,9 @@ MainWindow::~MainWindow()
56 55
     delete ui;
57 56
 }
58 57
 
59
-void MainWindow::showMW(bool doShow){
60
-    if (doShow){
58
+//This function show the main window and delete all the items created on the closed one or hide the mainwindow
59
+void MainWindow::mostrar(bool si){
60
+    if (si==true){
61 61
         show();
62 62
 
63 63
         // Deleting pointers and point them to NULL
@@ -79,13 +79,14 @@ void MainWindow::showMW(bool doShow){
79 79
 
80 80
         // Create the new window and connecting it again with the signal
81 81
         window = new secondwindow;
82
-        connect(window, SIGNAL(closeIt(bool)), this, SLOT(showMW(bool)));
82
+        connect(window, SIGNAL(cerrado(bool)), this, SLOT(mostrar(bool)));
83 83
     }
84 84
     else hide();
85 85
 }
86 86
 
87
-
88
-void MainWindow::setOption(QString str){
87
+//It is a slot that reads what item of the combo box was selected and save it
88
+//into a member
89
+void MainWindow::whatOption(QString str){
89 90
     option = str;
90 91
 }
91 92
 
@@ -99,8 +100,212 @@ void MainWindow::clearLines(){
99 100
     score1 = score2 = 0;
100 101
 }
101 102
 
103
+//It forces the input 1 to be valid
104
+void MainWindow::RPSnormalizer1(QString str){
105
+    //For every character in the string only allow
106
+    //the character 'R' for rock, 'P' for paper and
107
+    //'S' for scissors. Delete all the other characters
108
+    //different from this three, and if is 'r', 'p' or 's'
109
+    //make it uppercase.
110
+    for (int i = 0; i< str.size(); i++){
111
+        if      (str[i] == 'r'){
112
+            str[i] = 'R';
113
+        }
114
+        else if (str[i] == 'p'){
115
+            str[i] = 'P';
116
+        }
117
+        else if (str[i] == 's'){
118
+            str[i] = 'S';
119
+        }
120
+
121
+        else if (str[i] == 'R' || str[i] == 'P' ||
122
+                 str[i] == 'S');//then its ok, do nothing
123
+        else{
124
+            str = str.mid(0,i).append(str.mid(i+1));
125
+        }
126
+    }
127
+
128
+    line[0]->setText(str);
129
+}
130
+
131
+//It forces the input 2 to be valid
132
+void MainWindow::RPSnormalizer2(QString str){
133
+    for (int i = 0; i< str.size(); i++){
134
+        if      (str[i] == 'r'){
135
+            str[i] = 'R';
136
+        }
137
+        else if (str[i] == 'p'){
138
+            str[i] = 'P';
139
+        }
140
+        else if (str[i] == 's'){
141
+            str[i] = 'S';
142
+        }
143
+        else if (str[i] == 'R' || str[i] == 'P' ||
144
+                 str[i] == 'S');//then its ok, do nothing
145
+        else{
146
+            str = str.mid(0,i).append(str.mid(i+1));
147
+        }
148
+    }
149
+
150
+    line[1]->setText(str);
151
+}
152
+
153
+//It forces the input 3 to be valid
154
+void MainWindow::RPSnormalizer3(QString str){
155
+    //Verify that the string do not contains other thing than
156
+    //numbers
157
+    for (int i = 0; i< str.size(); i++){
158
+        if (!str[i].isDigit()){
159
+            str = str.mid(0,i).append(str.mid(i+1));
160
+        }
161
+    }
162
+
163
+    //Left zeros do not count, delete them
164
+    while (str[0] == '0'){
165
+        str = str.mid(1);
166
+    }
167
+
168
+    //If the player exagerates the number of games to win
169
+    //change the string to the maximum number allowed
170
+    if (str.toInt() > 150){
171
+        str = "150";
172
+    }
173
+
174
+    line[2]->setText(str);
175
+}
176
+
177
+//It forces the input to be valid
178
+void MainWindow::CheckWnormalizer(QString str){
179
+    //Just allow numbers
180
+    for (int i = 0; i< str.size(); i++){
181
+        if (!str[i].isDigit()){
182
+            str = str.mid(0,i).append(str.mid(i+1));
183
+        }
184
+    }
185
+
186
+    //Zeros on the left side do not count (delete them)
187
+    while (str[0] == '0'){
188
+        str = str.mid(1);
189
+    }
190
+
191
+    //The maximum is 999,999,999
192
+    if (str.toDouble() > 999999999){
193
+        str = "999999999";
194
+    }
195
+
196
+    line[0]->setText(str);
197
+}
198
+
199
+
200
+
201
+//It forces the first input of Zulu to be valid
202
+void MainWindow::Zulunormalizer1(QString str){
203
+    //Just allow numbers to be written
204
+    for (int i = 0; i< str.size(); i++){
205
+        if (!str[i].isDigit()){
206
+            str = str.mid(0,i).append(str.mid(i+1));
207
+        }
208
+    }
209
+
210
+    //The maximum here is 2359, so force it to be the
211
+    //maximum when the user write a larger number
212
+    if (str.toInt() > 2359){
213
+        str = "2359";
214
+    }
215
+
216
+    line[0]->setText(str);
217
+}
218
+
219
+//It forces the second input of Zulu to be valid
220
+void MainWindow::Zulunormalizer2(QString str){
221
+    //Just allow one character to be written
222
+    if (str.size() > 1){
223
+        str = str[1];
224
+    }
225
+
226
+    //If that only character is 'e', 'c', 'm' or 'p'
227
+    //the uppercase it
228
+    if (str[0] == 'e' || str[0] == 'c' ||
229
+            str[0] == 'm' || str[0] == 'p'){
230
+        str = str[0].toUpper();
231
+    }
232
+    //If we get here is because the character is not
233
+    //the lowercase letters allowed... so if they are
234
+    //not the uppercase letters that we admit we have
235
+    //to delete it.
236
+    else if (str[0] != 'E' || str[0] != 'C' ||
237
+             str[0] != 'M' || str[0] != 'P'){
238
+        str = "";
239
+    }
240
+
241
+    line[1]->setText(str);
242
+}
243
+
244
+//It forces the first input of APFT to be valid
245
+void MainWindow::APFTnormalizer1(QString str){
246
+    //Just admit numbers, delete the other type of
247
+    //characters
248
+    for (int i = 0; i< str.size(); i++){
249
+        if (!str[i].isDigit()){
250
+            str = str.mid(0,i).append(str.mid(i+1));
251
+        }
252
+    }
253
+
254
+    //Left zeros are not valid
255
+    while (str[0] == '0'){
256
+        str = str.mid(1);
257
+    }
258
+
259
+    line[0]->setText(str);
260
+}
261
+
262
+//It forces the second input of APFT to be valid
263
+void MainWindow::APFTnormalizer2(QString str){
264
+    //Just allow the numbers to be written
265
+    for (int i = 0; i< str.size(); i++){
266
+        if (!str[i].isDigit()){
267
+            str = str.mid(0,i).append(str.mid(i+1));
268
+        }
269
+    }
270
+
271
+    //Left-hand zeros? Delete them
272
+    while (str[0] == '0'){
273
+        str = str.mid(1);
274
+    }
275
+
276
+    line[1]->setText(str);
277
+}
278
+
279
+//It forces the third input of APFT to be valid
280
+void MainWindow::APFTnormalizer3(QString str){
281
+    //Allow just numbers on the string only if the
282
+    //character is not in the position 2
283
+    for (int i = 0; i< str.size(); i++){
284
+        if (!str[i].isDigit() && i != 2){
285
+            str = str.mid(0,i).append(str.mid(i+1));
286
+        }
287
+    }
288
+
289
+    //Then if there is a character in the position 2
290
+    //and it is not ':', then add it between the
291
+    //position 1 and 3
292
+    if (str.size() > 2 && str[2] != ':'){
293
+        while (str.size()>2 && !str[2].isDigit()){
294
+            str = str.mid(0,2).append(str.mid(3));
295
+        }
296
+        str = str.mid(0, 2).append(':').append(str.mid(2));
297
+    }
298
+    //If the size exceeds 5, then take the first five
299
+    //so then we will have the format mm:ss
300
+    if (str.size() > 5){
301
+        str = str.mid(0, 5);
302
+    }
102 303
 
103
-void MainWindow::callOneOfTheSorts(){
304
+    line[2]->setText(str);
305
+}
306
+
307
+//Checks which version of sort is selected and call it
308
+void MainWindow::sorts(){
104 309
     QString a = line[0]->text();
105 310
     QString b = line[1]->text();
106 311
     QString c = line[2]->text();
@@ -129,7 +334,10 @@ void MainWindow::callOneOfTheSorts(){
129 334
 }
130 335
 
131 336
 
132
-void MainWindow::callOneOfTheRPS(){
337
+
338
+
339
+//Checks which version of RPS is selected and call it
340
+void MainWindow::RPSs(){
133 341
 
134 342
     QString p1 = this->cmbPlayer01->currentText();
135 343
     QString p2 = this->cmbPlayer02->currentText();
@@ -152,6 +360,7 @@ void MainWindow::callOneOfTheRPS(){
152 360
 
153 361
     QString st;
154 362
 
363
+    qDebug() << winnerNum;
155 364
 
156 365
     switch(winnerNum) {
157 366
         case 1:  st = "Player 1"; break;
@@ -162,11 +371,14 @@ void MainWindow::callOneOfTheRPS(){
162 371
 
163 372
     line[0]->setText(st);
164 373
 
374
+
375
+
165 376
 }
166 377
 
378
+#include <QTimer>
167 379
 
168 380
 void MainWindow::paintDice() {
169
-    this->timerCounter++;
381
+    qDebug() << this->timerCounter++;
170 382
     int a, b;
171 383
     a = rand()%6;
172 384
     b = rand()%6;
@@ -187,12 +399,16 @@ void MainWindow::paintDice() {
187 399
     }
188 400
 }
189 401
 
402
+//Checks which version of dice is selected and call it
403
+void MainWindow::dices(){
404
+    // [rafa] Voy a hacer la animación aqui
405
+
190 406
 
191
-void MainWindow::callOneOfTheDices(){
192 407
 
193 408
     for (int i = 1; i <= 6; i++)
194 409
         this->diceImages.push_back(QImage(":/images/resources/d" + QString::number(i) + ".png"));
195 410
 
411
+
196 412
     aTimer = new QTimer;
197 413
     aTimer->setInterval(100);
198 414
     aTimer->setSingleShot(false);
@@ -204,38 +420,8 @@ void MainWindow::callOneOfTheDices(){
204 420
 }
205 421
 
206 422
 
207
-
208
-
209
-//========================================================
210
-// Functions for the dice roller
211
-//========================================================
212
-
213
-
214
-void MainWindow::diceAlpha(){
215
-    int total = diceFinal01 + diceFinal02 + 2;
216
-    line[0]->setText(QString::number(total));
217
-}
218
-
219
-
220
-void MainWindow::diceBeta(){
221
-    int total = diceFinal01 + diceFinal01 + 2;
222
-    line[0]->setText(QString::number(total));
223
-}
224
-
225
-
226
-void MainWindow::diceGamma(){
227
-    int total = diceFinal01 - diceFinal02;
228
-    line[0]->setText(QString::number(total));
229
-}
230
-
231
-
232
-void MainWindow::diceDelta(){
233
-    int total = diceFinal01 + diceFinal02;
234
-    line[0]->setText(QString::number(total));
235
-}
236
-
237
-
238
-void MainWindow::callOneOfTheChecks(){
423
+//Checks which version of check-writer is selected and call it
424
+void MainWindow::checkWs(){
239 425
     unsigned int qty;
240 426
     if (!validateCheckQty(line[0]->text(),qty)) {
241 427
         QMessageBox::warning(this, "Alert",
@@ -252,7 +438,8 @@ void MainWindow::callOneOfTheChecks(){
252 438
         line[1]->setText( checkWDelta(qty) );
253 439
 }
254 440
 
255
-void MainWindow::callOneOfTheZulus(){
441
+//Checks which version of zulu is selected and call it
442
+void MainWindow::zulus(){
256 443
     QString zuluTime = line[0]->text();
257 444
     QString zuluZone = line[1]->text();
258 445
     int hours, minutes;
@@ -260,7 +447,7 @@ void MainWindow::callOneOfTheZulus(){
260 447
     if (!validZuluTime(zuluTime, zuluZone, hours, minutes) ) {
261 448
 
262 449
         QMessageBox::warning(this, "Alert",
263
-                             "Either Zulu Time or Zone is not valid.");
450
+                             "Either Zulu Time or Zone is not valid");
264 451
         line[2]->setText("Error");
265 452
         return;
266 453
     }
@@ -275,7 +462,23 @@ void MainWindow::callOneOfTheZulus(){
275 462
 
276 463
 }
277 464
 
465
+//Checks which version of APFT is selected and call it
466
+void MainWindow::APFTs(){
467
+    if (option == "Version Alpha"){
468
+        APFTAlpha();
469
+    }
470
+    else if (option == "Version Beta"){
471
+        APFTBeta();
472
+    }
473
+    else if (option == "Version Gamma"){
474
+        APFTGamma();
475
+    }
476
+    else{
477
+        APFTDelta();
478
+    }
479
+}
278 480
 
481
+//Here is what happend when Sort-button is clicked
279 482
 void MainWindow::on_SortsButton_clicked()
280 483
 {
281 484
     //Create a new QComboBox and add the items in it
@@ -322,18 +525,19 @@ void MainWindow::on_SortsButton_clicked()
322 525
 
323 526
     //Here we connect the signals of the widgets generated
324 527
     //by code to their respective functions
325
-    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(setOption(QString)));
326
-    connect(button[0], SIGNAL(clicked()), this, SLOT(callOneOfTheSorts()));
528
+    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(whatOption(QString)));
529
+    connect(button[0], SIGNAL(clicked()), this, SLOT(sorts()));
327 530
     connect(button[1], SIGNAL(clicked()), this, SLOT(clearLines()));
328 531
 
329 532
     //Now that we have set our new window, we hide the main-window
330 533
     //and show the new one. The new-window has a signal that
331 534
     //notify when it was closed so we can shor the main-window
332 535
     window->setLayout(layout);
333
-    showMW(false);
536
+    mostrar(false);
334 537
     window->show();
335 538
 }
336 539
 
540
+//Here is what happend when Dice-button is clicked
337 541
 void MainWindow::on_DiceButton_clicked()
338 542
 {
339 543
     //Create a new QComboBox and add the items in it
@@ -377,17 +581,18 @@ void MainWindow::on_DiceButton_clicked()
377 581
 
378 582
     //Here we connect the signals of the widgets generated
379 583
     //by code to their respective functions
380
-    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(setOption(QString)));
381
-    connect(button[0], SIGNAL(clicked()), this, SLOT(callOneOfTheDices()));
584
+    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(whatOption(QString)));
585
+    connect(button[0], SIGNAL(clicked()), this, SLOT(dices()));
382 586
 
383 587
     //Now that we have set our new window, we hide the main-window
384 588
     //and show the new one. The new-window has a signal that
385 589
     //notify when it was closed so we can shor the main-window
386 590
     window->setLayout(layout);
387
-    showMW(false);
591
+    mostrar(false);
388 592
     window->show();
389 593
 }
390 594
 
595
+//Here is what happend when RPS-button is clicked
391 596
 void MainWindow::on_RPSButton_clicked()
392 597
 {
393 598
     //Create a new QComboBox and add the items in it
@@ -405,9 +610,17 @@ void MainWindow::on_RPSButton_clicked()
405 610
     cmbPlayer01->addItem("scisors");    cmbPlayer02->addItem("scisors");
406 611
 
407 612
 
613
+
614
+
615
+
408 616
     //The buttons needed here are the 'play' and 'clear' buttons
409 617
     button[0] = new QPushButton("Play");
618
+//    button[1] = new QPushButton("Clear");
410 619
 
620
+    //3 inputs and 1 output
621
+//    for (int i = 0; i<4; i++){
622
+//        line[i] = new QLineEdit;
623
+//    }
411 624
     line[0] = new QLineEdit;
412 625
     //The user is not able to write on the output line
413 626
     line[0]->setEnabled(false);
@@ -415,7 +628,13 @@ void MainWindow::on_RPSButton_clicked()
415 628
     //Labels to let the user understand the app
416 629
     label[0] = new QLabel("Player 1's moves");
417 630
     label[1] = new QLabel("Player 2's moves");
631
+//    label[2] = new QLabel("How many games to win:");
418 632
     label[2] = new QLabel("Winner:");
633
+//    label[4] = new QLabel("Tournament:");
634
+//    //lines for score
635
+//    line[4] = new QLineEdit;
636
+//    line[4]->setEnabled(false);
637
+
419 638
 
420 639
     //We create a new layout and insert the comboBox to it
421 640
     int row = 0;
@@ -432,18 +651,21 @@ void MainWindow::on_RPSButton_clicked()
432 651
 
433 652
     //Here we connect the signals of the widgets generated
434 653
     //by code to their respective functions
435
-    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(setOption(QString)));
436
-    connect(button[0], SIGNAL(clicked()), this, SLOT(callOneOfTheRPS()));
654
+    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(whatOption(QString)));
655
+    connect(button[0], SIGNAL(clicked()), this, SLOT(RPSs()));
437 656
 
438 657
     //Now that we have set our new window, we hide the main-window
439 658
     //and show the new one. The new-window has a signal that
440 659
     //notify when it was closed so we can shor the main-window
441 660
     window->setLayout(layout);
442
-    showMW(false);
661
+    mostrar(false);
443 662
     window->show();
663
+//    score1 = score2 = 0;
444 664
 }
445 665
 
446 666
 
667
+
668
+//Here is what happend when Zulu-button is clicked
447 669
 void MainWindow::on_ZuluButton_clicked()
448 670
 {
449 671
     //Create a new QComboBox and add the items in it
@@ -487,9 +709,9 @@ void MainWindow::on_ZuluButton_clicked()
487 709
 
488 710
     //Here we connect the signals of the widgets generated
489 711
     //by code to their respective functions
490
-    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(setOption(QString)));
712
+    connect(method, SIGNAL(currentIndexChanged(QString)), this, SLOT(whatOption(QString)));
491 713
     connect(button[0], SIGNAL(clicked()), this, SLOT(clearLines()));
492
-    connect(button[1], SIGNAL(clicked()), this, SLOT(callOneOfTheZulus()));
714
+    connect(button[1], SIGNAL(clicked()), this, SLOT(zulus()));
493 715
 
494 716
     // Rafa 2014-09-16 - Validation will be done when button is clicked
495 717
     //    connect(line[0], SIGNAL(textEdited(QString)), this, SLOT(Zulunormalizer1(QString)));
@@ -499,7 +721,6 @@ void MainWindow::on_ZuluButton_clicked()
499 721
     //and show the new one. The new-window has a signal that
500 722
     //notify when it was closed so we can shor the main-window
501 723
     window->setLayout(layout);
502
-    showMW(false);
503 724
     window->show();
504 725
 }
505 726
 

+ 45
- 152
mainwindow.h Datei anzeigen

@@ -28,183 +28,76 @@ public:
28 28
     explicit MainWindow(QWidget *parent = 0);
29 29
     ~MainWindow();
30 30
 
31
-
32
-    /// \fn diceAlpha
33
-    /// \~English
34
-    /// \brief Computes the dice total based on the values of the dice.
35
-    /// \~Spanish
36
-    /// \brief Computa el total de puntos usando los valores de los dados.
37 31
     void diceAlpha();
38
-
39
-
40
-    /// \fn diceBeta
41
-    /// \~English
42
-    /// \brief Computes the dice total based on the values of the dice.
43
-    /// \~Spanish
44
-    /// \brief Computa el total de puntos usando los valores de los dados.
45 32
     void diceBeta();
46
-
47
-    /// \fn diceGamma
48
-    /// \~English
49
-    /// \brief Computes the dice total based on the values of the dice.
50
-    /// \~Spanish
51
-    /// \brief Computa el total de puntos usando los valores de los dados.
52 33
     void diceGamma();
53
-
54
-    /// \fn diceDelta
55
-    /// \~English
56
-    /// \brief Computes the dice total based on the values of the dice.
57
-    /// \~Spanish
58
-    /// \brief Computa el total de puntos usando los valores de los dados.
59 34
     void diceDelta();
60 35
 
36
+    void APFTAlpha();
37
+    void APFTBeta();
38
+    void APFTGamma();
39
+    void APFTDelta();
61 40
 
62 41
 private slots:
63
-
64
-
65
-    /// \fn on_SortsButton_clicked
66
-    /// \~English
67
-    /// \brief Called when Sort-button is clicked. Creates controls for secondary window,
68
-    /// displays it, and hides the main window.
69
-    /// \~Spanish
70
-    /// \brief Esta función es llamada cuando el usuario cliquea el boton de Sort. 
71
-    /// Crea los controles de la ventana secundaria. muestra la ventana secundaria 
72
-    /// y esconde la ventana principal.
73 42
     void on_SortsButton_clicked();
74
-
75
-    /// \fn on_DiceButton_clicked
76
-    /// \~English
77
-    /// \brief Called when Dice button is clicked. Creates controls for secondary window,
78
-    /// displays it, and hides the main window.
79
-    /// \~Spanish
80
-    /// \brief Esta función es llamada cuando el usuario cliquea el boton de Dice. 
81
-    /// Crea los controles de la ventana secundaria. muestra la ventana secundaria 
82
-    /// y esconde la ventana principal.
83 43
     void on_DiceButton_clicked();
84
-
85
-    /// \fn on_RPSButton_clicked
86
-    /// \~English
87
-    /// \brief Called when RPS button is clicked. Creates controls for secondary window,
88
-    /// displays it, and hides the main window.
89
-    /// \~Spanish
90
-    /// \brief Esta función es llamada cuando el usuario cliquea el boton de RPS. 
91
-    /// Crea los controles de la ventana secundaria. muestra la ventana secundaria 
92
-    /// y esconde la ventana principal.  
93 44
     void on_RPSButton_clicked();
45
+    void on_ZuluButton_clicked();
94 46
 
47
+    void mostrar(bool si);
95 48
 
96
-    /// \fn on_ZuluButton_clicked
97
-    /// \~English
98
-    /// \brief Called when Zulu time button is clicked. Creates controls for secondary window,
99
-    /// displays it, and hides the main window.
100
-    /// \~Spanish
101
-    /// \brief Esta función es llamada cuando el usuario cliquea el boton de Zulu time. 
102
-    /// Crea los controles de la ventana secundaria. muestra la ventana secundaria 
103
-    /// y esconde la ventana principal.  
104
-    void on_ZuluButton_clicked();
49
+    void whatOption(QString str);
105 50
 
106
-    /// \fn showMW
107
-    /// \~English
108
-    /// \brief This function either (1) shows the main window and deletes all the items created on 
109
-    /// the closed one or (2) hides the mainwindow
110
-    /// \param doShow if true then show the main window, else hide it. 
111
-    /// \~Spanish
112
-    /// \brief Esta función hace una de dos: (1) muestra la ventana principal y borra
113
-    /// todas los elementos creados en la secundaria, o (2) esconde la ventana principal
114
-    /// \param doShow si es true muestra la ventana principal, de lo contrario la esconde. 
115
-    void showMW(bool doShow);
116
-
117
-
118
-    /// \fn setOption
119
-    /// \~English
120
-    /// \brief A slot that reads what item of the combo box was selected and saves it
121
-    /// to a data member.
122
-    /// \~Spanish
123
-    /// \brief Un slot que lee la selección del combobox y lo guarda a un data member.
124
-    void setOption(QString str);
125
-
126
-
127
-    /// \fn clearLines
128
-    /// \~English
129
-    /// \brief Clear the text boxes in the GUIs.
130
-    /// \~Spanish
131
-    /// \brief Limpia las cajas de texto en los GUIs.
132 51
     void clearLines();
133 52
 
134
-    /// \fn callOneOfTheSorts
135
-    /// \~English
136
-    /// \brief Reads the version combobox, validates the inputs, and calls the
137
-    /// alpha, beta, gamma or delta sort function.
138
-    /// \~Spanish
139
-    /// \brief Lee el combobox, valida los inputs y llama a la versión
140
-    /// alpha, beta, gamma o delta de las funciones de sort
141
-    void callOneOfTheSorts();
142
-
143
-
144
-    /// \fn callOneOfTheRPS
145
-    /// \~English
146
-    /// \brief Reads the version combobox, validates the inputs, and calls the
147
-    /// alpha, beta, gamma or delta RPS function.
148
-    /// \~Spanish
149
-    /// \brief Lee el combobox, valida los inputs y llama a la versión
150
-    /// alpha, beta, gamma o delta de las funciones de RPS (piedra, papel y tijera)
151
-    void callOneOfTheRPS();
152
-
153
-
154
-    /// \fn callOneOfTheDices
155
-    /// \~English
156
-    /// \brief Reads the version combobox, validates the inputs, and calls the
157
-    /// alpha, beta, gamma or delta dice function.
158
-    /// \~Spanish
159
-    /// \brief Lee el combobox, valida los inputs y llama a la versión
160
-    /// alpha, beta, gamma o delta de las funciones de "dice".
161
-    void callOneOfTheDices();
162
-
163
-
164
-    /// \fn callOneOfTheChecks
165
-    /// \~English
166
-    /// \brief Reads the version combobox, validates the inputs, and calls the
167
-    /// alpha, beta, gamma or delta check function
168
-    /// \~Spanish
169
-    /// \brief Lee el combobox, valida los inputs y llama a la versión
170
-    /// alpha, beta, gamma o delta de las funciones de cheques.
171
-    void callOneOfTheChecks();
172
-
173
-
174
-    /// \fn callOneOfTheZulus
175
-    /// \~English
176
-    /// \brief Reads the version combobox, validates the inputs, and calls the
177
-    /// alpha, beta, gamma or delta zulu time function
178
-    /// \~Spanish
179
-    /// \brief Lee el combobox, valida los inputs y llama a la versión
180
-    /// alpha, beta, gamma o delta de las funciones de zulu time.
181
-    void callOneOfTheZulus();
182
-
183
-
184
-    /// \fn paintDice
185
-    /// \~English
186
-    /// \brief This function is called on every timer tick to "animate" the dice.
187
-    /// \~Spanish
188
-    /// \brief Función invocada en cada tick del timer para "animar" el dado.
53
+    void RPSnormalizer1(QString str);
54
+
55
+    void RPSnormalizer2(QString str);
56
+
57
+    void RPSnormalizer3(QString str);
58
+
59
+    void CheckWnormalizer(QString str);
60
+
61
+    void Zulunormalizer1(QString str);
62
+
63
+    void Zulunormalizer2(QString str);
64
+
65
+    void APFTnormalizer1(QString str);
66
+
67
+    void APFTnormalizer2(QString str);
68
+
69
+    void APFTnormalizer3(QString str);
70
+
71
+    void sorts();
72
+
73
+    void RPSs();
74
+
75
+    void dices();
76
+
77
+    void checkWs();
78
+
79
+    void zulus();
80
+
81
+    void APFTs();
82
+
189 83
     void paintDice();
190 84
 
191 85
 private:
192
-    Ui::MainWindow  *ui;
193
-    secondwindow    *window;
194
-    QGridLayout     *layout;
195
-    QPushButton     *button[2];
196
-    QLineEdit       *line[7];
197
-    QLabel          *label[7];
198
-    QComboBox       *method, *cmbPlayer01, *cmbPlayer02;
199
-    QTimer          *aTimer;
200
-
86
+    Ui::MainWindow *ui;
87
+    secondwindow *window;
88
+    QGridLayout *layout;
89
+    QPushButton *button[2];
201 90
     int buttonSize;
91
+    QLineEdit *line[7];
202 92
     int lineSize;
93
+    QLabel *label[7];
203 94
     int labelSize;
95
+    QComboBox *method, *cmbPlayer01, *cmbPlayer02;
204 96
     QString option;
205 97
     QImage dice1;
206 98
     QImage dice2;
207 99
     int diceFinal01, diceFinal02;
100
+    QTimer *aTimer;
208 101
     int timerCounter;
209 102
     int score1, score2;
210 103
 

+ 4
- 3
mainwindow.ui Datei anzeigen

@@ -127,7 +127,7 @@
127 127
        <x>30</x>
128 128
        <y>54</y>
129 129
        <width>641</width>
130
-       <height>16</height>
130
+       <height>4</height>
131 131
       </rect>
132 132
      </property>
133 133
      <property name="styleSheet">
@@ -151,7 +151,9 @@
151 151
      </rect>
152 152
     </property>
153 153
     <property name="styleSheet">
154
-     <string notr="true">background-image: url(:/images/resources/logo.png);</string>
154
+     <string notr="true">background-image: url(/home/rgb/Desktop/eip/CaesarCipher/logo.png);
155
+border: 0px;
156
+</string>
155 157
     </property>
156 158
     <property name="frameShape">
157 159
      <enum>QFrame::StyledPanel</enum>
@@ -159,7 +161,6 @@
159 161
     <property name="frameShadow">
160 162
      <enum>QFrame::Raised</enum>
161 163
     </property>
162
-    <zorder>label</zorder>
163 164
    </widget>
164 165
   </widget>
165 166
  </widget>

+ 1
- 1
secondwindow.cpp Datei anzeigen

@@ -7,5 +7,5 @@ secondwindow::secondwindow(QWidget *parent) :
7 7
 }
8 8
 
9 9
 void secondwindow::closeEvent(QCloseEvent *){
10
-    emit closeIt(true);
10
+    emit cerrado(true);
11 11
 }

+ 1
- 26
secondwindow.h Datei anzeigen

@@ -7,37 +7,12 @@ class secondwindow : public QWidget
7 7
 {
8 8
     Q_OBJECT
9 9
 public:
10
-
11
-    /// \fn secondwindow
12
-    /// \~English
13
-    /// \brief Constructor.
14
-    /// \param parent this object's parent
15
-    /// \~Spanish
16
-    /// \brief Constructor
17
-    /// \param parent ventana padre
18 10
     explicit secondwindow(QWidget *parent = 0);
19 11
 
20 12
 signals:
21
-    /// \fn closeIt
22
-    /// \~English
23
-    /// \brief Just a signal that will be emitted when closing 
24
-	/// objects of this class
25
-	/// \param dummy this parameter is just for making this signal compatible with 
26
-    /// type of slot it will be connected.
27
-    /// \~Spanish
28
-    /// \brief Señal que será emitida al cerrar objetos de esta clase
29
-	/// \param dummy este parameterro existe para que la señal sea compatible con el
30
-	/// slot al que será conectada.
31
-    void closeIt(bool dummy);
13
+    void cerrado(bool si);
32 14
 
33 15
 protected:
34
-
35
-    /// \fn closeEvent
36
-    /// \~English
37
-    /// \brief Overloaded function that is called when an object of this class is closed.
38
-    /// \~Spanish
39
-    /// \brief Función sobrecargada que es invocada cuando se cierra un objeto de 
40
-    /// esta clase.  
41 16
     virtual void closeEvent(QCloseEvent *);
42 17
 
43 18
 public slots: