[English](#markdown-header-repetition-structures-tessellations) | [Español](#markdown-header-estructuras-de-repeticion-mosaicos) # Estructuras de repetición - Mosaicos ![main1.gif](images/main1.gif) ![main2.png](images/main2.png) ![main3.png](images/main3.png) Una de las ventajas de utilizar programas de computadoras es que podemos realizar tareas repetitivas fácilmente. Los ciclos como `for`, `while`, y `do-while` son estructuras de control que nos permiten repetir un conjunto de instrucciones. A estas estructuras también se les llama *estructuras de repetición*. En la experiencia de laboratorio de hoy practicarás el uso de ciclos anidados para producir patrones y mosaicos. ##Objetivos: 1. Practicar el uso de estructuras de repetición al construir patrones y mosaicos. 2. Reforzar las destrezas de uso de funciones y objetos. Esta experiencia de laboratorio es una adaptación de https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2. ##Pre-Lab: Antes de llegar al laboratorio debes haber: 1. Repasado los conceptos básicos relacionados a estructuras de repetición. 2. Estudiado los conceptos e instrucciones para la sesión de laboratorio, especialmente el uso de los métodos para: a. ajustar el tamaño de las ventanas, b. colocar las teselaciones en posiciones específicas, c. rotar teselaciones. 3. Tomado el quiz Pre-Lab que se encuentra en Moodle. --- --- ##Teselaciones Una *teselación* ("tessellation" o "tilling") es un mosaico que se crea repitiendo una figura para cubrir una superficie sin dejar huecos y sin solapamientos. Una *teselación regular* es una figura que se forma repitiendo un mismo *polígono regular*, como triángulos, cuadrados o hexágonos. (Un polígono regular es un polígono cuyos lados son congruentes y en el que los ángulos que forman los lados son congruentes.) --- ![figure1.gif](images/figure1.gif) **Figura 1** - Las únicas teselaciones regulares posibles obtenidas usando triángulos, cuadrados o hexágonos. --- ##Biblioteca El proyecto `Tessellations.pro` disponible en `http://bitbucket.org/eip-uprrp/repetitions1-tessellations` contiene la clase `Tessellation`, que es una abstracción de una teselación con cuadrados, y la clase `DrawingWindow`. El código de muestra en la Figura 2 crea un `DrawingWindow` llamado `w`, un `Tessellation` llamado `t` y coloca la teselación en la posición (50,100). Nota que el método `addTessellation` de la clase `DrawingWindow` debe ser invocado para que la teselación se dibuje. --- ```cpp int main(int argc, char *argv[]) { QApplication a(argc, argv); DrawingWindow w; // crea el objeto w de la clase DrawingWindow w.resize(300, 300); w.show(); Tessellation t; // crea el objeto t de la clase Tessellation t.move(50,100); // dice la posición de la teselacion w.addTessellation(t); // añade la teselacion a la ventana return a.exec(); } ``` **Figura 2.** Código en función `main` para crear ventana y teselación. --- La ventana que se obtiene con el código de la Figura 2 es similar a la ventana en la Figura 3. Las flechas y los números 50 y 100 ilustran los espacios entre la esquina superior izquierda de la teselación y los bordes de la ventana. La esquina superior izquierda de la teselación está en la posición (50,100). --- ![figure3.png](images/figure3.png) **Figura 3.** Ventana con teselación en la posición (50,100). --- **Ejemplo 1.** El código de la Figura 4 contiene una función `foo` para dibujar cuatro teselaciones en las posiciones (0,0), (50,50), (100,100), and (150,150), con rotaciones de la figura original de $$0^\circ, 90^\circ, 180^\circ y 270^\circ$$ (a favor de las manecillas del reloj). --- ```cpp int foo(DrawingWindow &w) { int rot = 0; for (int i = 0; i < 4; i++) { Tessellation t; t.setRotation(rot); t.move(i * 50, i * 50); w.addTessellation(t); rot += 90; } } int main(int argc, char *argv[]) { QApplication a(argc, argv); DrawingWindow w; w.resize(300, 300); w.show(); foo(w); return a.exec(); } ``` **Figura 4.** Código de la función `foo` que dibuja cuatro teselaciones. --- Observa como la función `foo` necesita recibir una referencia al objeto `w` de la clase `DrawingWindow` ya que está invocando el método `addTessellation` de esta clase en cada iteración del ciclo. La figura que se obtiene es similar a la de la Figura 5. --- ![figure5.png](images/figure5.png) **Figura 5.** Teselaciones dibujadas por la función `foo` en el código de la Figura 4. --- **Ejemplo 2.** El código de la Figura 6 nos muestra un ejemplo del uso de ciclos anidados para crear teselaciones. --- ```cpp int fah(DrawingWindow &w) { int rot = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Tessellation t; t.move(i * 50, j * 50); t.setRotation(rot); w.addTessellation(t); } rot += 90; } } ``` **Figura 6.** Código de la función `fah` que utiliza ciclos anidados para dibujar cuatro teselaciones. La figura que se obtiene es similar a la de la Figura 7. --- ![figure7.png](images/figure7.png) **Figura 7.** Teselaciones dibujadas por la función `fah` en el código de la Figura 6. --- --- --- !INCLUDE "../../eip-diagnostic/tesselations/es/diag-tesselations-01.html" !INCLUDE "../../eip-diagnostic/tesselations/es/diag-tesselations-02.html" --- --- ##Sesión de laboratorio: En la experiencia de laboratorio de hoy practicarás el uso de ciclos anidados para crear distintas teselaciones. ###Ejercicio 1: Estudiar ciclo que produce teselaciones ####Instrucciones 1. Carga a Qt el proyecto `Tessellations` haciendo doble "click" en el archivo `Tessellations.pro` en el directorio `Documents/eip/Repetitions-Tessellations` de tu computadora. También puedes ir a `http://bitbucket.org/eip-uprrp/repetitions-tessellations` para descargar la carpeta `Repetitions-Tessellations` a tu computadora. 2. El proyecto `Tessellations.pro` contiene las clases `Tessellation` y `DrawingWindow` y la función `foo`. Configura el proyecto y corre el programa. Debes observar una pantalla parecida a la Figura 5. Esta figura se crea con la función `foo` mostrada en la Figura 4 y explicada en el Ejemplo 1. La función `foo` es invocada desde `main()`. En esta experiencia de laboratorio solo estarás haciendo cambios a la función `main()`. Estudia nuevamente la función `foo` y nota la creación de los objetos de la clase `Tessellations`, el uso del método `setRotation` y el método `move` para colocar la teselación en la posición deseada. Nota cómo las instrucciones en el ciclo `for` de la función utilizan el contador del ciclo para determinar la posición del cuadrado y como se incrementa el valor de la rotación. También nota que necesitas utilizar el método `addTessellation` para que la teselación se añada en la ventana `w`. ###Ejercicio 2: Crear función y teselación `herringbone` ####Instrucciones 1. Crea una función `herringbone` que produzca la teselación de la Figura 8. El tamaño de la ventana es 400x400. El tamaño de cada cuadrado de la teselación es su tamaño por defecto: 50x50. --- ![figure8.png](images/figure8.png) **Figura 8.** Teselación que debe dibujar la función `herringbone`. --- 2. Comenta la **invocación** de la función `foo`. 3. Invoca la función `herringbone` desde `main()` y corre tu programa para que veas la teselación que creaste. ###Ejercicio 3: Crear función y teselación `zigzag` ####Instrucciones 1. Crea una función `zigzag` que produzca la teselación de la Figura 9. --- ![figure9.png](images/figure9.png) **Figura 9.** Teselación que debe dibujar la función `zigzag`. --- 2. Comenta la invocación de la función `herringbone`. 3. Invoca la función `zigzag` desde `main()` y corre tu programa para que veas la teselación que creaste. ###Ejercicio 4: Crear función y teselación `diamond` ####Instrucciones 1. Crea una función `diamond` que produzca la teselación de la Figura 10. --- ![figure10.png](images/figure10.png) **Figura 10.** Teselación que debe dibujar la función `diamond`. --- 2. Comenta la invocación de la función `zigzag`. 3. Invoca la función `diamond` desde `main()` y corre tu programa para que veas la teselación que creaste. --- --- ##Entrega Utiliza "Entrega" en Moodle para entregar el archivo `main.cpp` que contiene las funciones `herringbone`, `zigzag` y `diamond` que creaste en los Ejercicios 2, 3 y 4 y sus invocaciones. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa. --- --- ##Referencias [1] https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2. --- --- --- [English](#markdown-header-repetition-structures-tessellations) | [Español](#markdown-header-estructuras-de-repeticion-mosaicos) # Repetition Structures - Tessellations ![main1.gif](images/main1.gif) ![main2.png](images/main2.png) ![main3.png](images/main3.png) One of the advantages of using computer programs is that we can easily implement repetitive tasks. Structures such as the `for`, `while`, and `do-while` allow us to repeat a block of instructions as many times as needed. In this lab experience you will use `for` loops produce patterns and mosaics. ##Objectives: 1. Practice the use of repetition structures to make patterns and tessellations. 2. Strengthen the use of functions and objects. This laboratory experience is an adaptation of https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2. ##Pre-Lab: Before coming to the laboratory session you should have: 1. Reviewed the basic concepts related to repetition structures. 2. Studied the concepts and instructions for the laboratory session, especially the use of the methods for: a. adjusting the size of the windows, b. adjusting the position of the tessellations, c. rotate tessellations. 3. Taken the Pre-Lab quiz available through the course’s Moodle portal. --- --- ##Tessellations A tessellation is a mosaic that is created by repeating a figure to cover the surface without leaving empty spaces or overlapping the figures. A *regular tessellation* is a figure that is made by repeating the same *regular polygon*, like triangles, squares or hexagons. (A regular polygon is a polygon where all sides are congruent and the angles that form the sides are congruent.) --- ![figure1.gif](images/figure1.gif) **Figure 1** - The only regular tessellations possible obtained using triangles, squares and hexagons. --- ##Library The `Tessellations.pro` project available in `http://bitbucket.org/eip-uprrp/repetitions1-tessellations` contains the `Tessellation` class, which is an abstraction of a tessellation with squares, and the `DrawingWindow` class. The code shown in Figure 2 creates a `DrawingWindow` called `w`, a `Tesselation` called `t` and places the tessellation in position (50,100). Notice that the `addTessellation` method of the `DrawingWindow` class should be invoked to draw the tessellation. --- ```cpp int main(int argc, char *argv[]) { QApplication a(argc, argv); DrawingWindow w; // Creates the w object of the DrawingWindow class w.resize(300, 300); w.show(); Tessellation t; // Creates the t object of the Tessellation class t.move(50,100); // Sets the tessellation's position w.addTessellation(t); // Adds the tessellation to the window return a.exec(); } ``` **Figure 2.** Code in the `main` function to create a window and tessellation. --- The window that is obtained with the code in Figure 2 is similar to the window in Figure 3. The arrows and the numbers 50 and 100 illustrate the spaces between the tessellation's upper left corner and the window's borders. The tessellation's upper left corner is in the position (50,100). --- ![figure3.png](images/figure3.png) **Figure 3.** Window with the tessellation in the position (50,100). --- **Example 1.** The code in Figure 4 contains a `foo` function to draw four tessellations in the positions (0,0), (50,50), (100,100), and (150,150), with the original figure's rotation of $$0^\circ, 90^\circ, 180^\circ y 270^\circ$$ (clockwise). --- ```cpp int foo(DrawingWindow &w) { int rot = 0; for (int i = 0; i < 4; i++) { Tessellation t; t.setRotation(rot); t.move(i * 50, i * 50); w.addTessellation(t); rot += 90; } } int main(int argc, char *argv[]) { QApplication a(argc, argv); DrawingWindow w; w.resize(300, 300); w.show(); foo(w); return a.exec(); } ``` **Figure 4.** Code for the `foo` function that draws four tessellations. --- Observe how the `foo` function needs to receive a reference to the `w` object of the `DrawingWindow` class since its invoking the `addTessellation` method of the class in each iteration of the loop. The figure that is obtained is similar to the one in Figure 5. --- ![figure5.png](images/figure5.png) **Figure 5.** Tessellations drawn by the `foo` function in the code in Figure 4. --- **Example 2.** The code in Figure 6 shows an example of how to use nested loops to create tessellations. --- ```cpp int fah(DrawingWindow &w) { int rot = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { Tessellation t; t.move(i * 50, j * 50); t.setRotation(rot); w.addTessellation(t); } rot += 90; } } ``` **Figure 6.** Code for the `fah` function that uses nested loops to draw four tessellations. The figure that is obtained is similar to the one in Figure 7. --- ![figure7.png](images/figure7.png) **Figure 7.** Tessellations drawn by the `fah` function in the code in Figure 6. --- --- --- !INCLUDE "../../eip-diagnostic/tesselations/en/diag-tesselations-01.html" !INCLUDE "../../eip-diagnostic/tesselations/en/diag-tesselations-02.html" --- --- ##Laboratory Session In today's laboratory experience you will practice the use of nested loops to create different tessellations. ###Exercise 1: Study the loop that produces tessellations ####Instructions 1. Load the Qt project called `Tessellations` by double-clicking on the `Tessellations.pro` file in the `Documents/eip/Repetitions-Tessellations` folder of your computer. Alternatively, you may clone the git repository `http://bitbucket.org/eip-uprrp/repetitions-tessellations` to download the `Repetitions-Tessellations` folder to your computer. 2. The `Tessellations.pro` project contains the `Tessellations` and `DrawingWindow` classes and the `foo` function. Configure the project and run the program. You should see a window similar to the one in Figure 5. This figure is created with the `foo` function shown in Figure 4 and explained in Example 1. The `foo` function is invoked from `main()`. In this laboratory experience you will only be making changes to the `main()` function. Study the `foo` function once again and notice the creation of the objects from the `Tessellations` class, the use of the `setRotation` method, and the `move` method to set the tessellation in the desired position. Notice how the instructions in the `for` loop in the function use the loop's counter to determine the square's position and how the rotation's value is incremented. Also notice that you will need to use the `addTessellation` method to add the tessellation to the `w` window. ###Exercise 2: Create the `herringbone` function and tessellation ####Instructions 1. Create a `herringbone` function that produces the tessellation in Figure 8. The size of the window is 400x400. The size of each square in the tessellation is its size by default: 50x50. --- ![figure8.png](images/figure8.png) **Figure 8.** Tessellation that the `herringbone` function should draw. --- 2. Comment the **invocation** of the `foo` function. 3. Invoke the `herringbone` function from `main()` and run the program so you can see the tessellation you created. ###Exercise 3: Create the `zigzag` function and tessellation ####Instructions 1. Create a `zigzag` function that produces the tessellation in Figure 9. --- ![figure9.png](images/figure9.png) **Figure 9.** Tessellation that the `zigzag` function should draw. --- 2. Comment the invocation of the `herringbone` function. 3. Invoke the `zigzag` function from `main()` and run the program so you can see the tessellation you created. ###Exercise 4: Create the `diamond` function and tessellation ####Instructions 1. Create a `diamond` function that produces the tessellation in Figure 10. --- ![figure10.png](images/figure10.png) **Figure 10.** Tessellation that the `diamond` function should draw. --- 2. Comment the invocation of the `zigzag` function. 3. Invoke the `diamond` function from `main()` and run the program so you can see the tessellation you created. --- --- ##Deliverables Use "Deliverables" in Moodle to upload the `main.cpp` file that contains the `herringbone`, `zigzag` and `diamond` functions that you created in Exercises 2, 3, and 4. Remember to use good programming techniques, include the names of the programmers involved, and to document your program. --- --- ##References [1] https://sites.google.com/a/wellesley.edu/wellesley-cs118-spring13/lectures-labs/lab-2.