martes, 23 de enero de 2018

1.1.1 Funciones de un DBA

Un administrador de bases de datos (también conocido como DBA, en inglés database administrator) es aquel profesional que administra las tecnologías de la información y la comunicación, siendo responsable de los aspectos técnicos, tecnológicos, científicos, inteligencia de negocios y legales de bases de datos, y de la calidad de datos.

Las responsabilidades incluyen el diseño, implementación y mantenimiento del sistema de base de datos; el establecimiento de políticas y procedimientos relativos a la gestión, la seguridad, el mantenimiento y el uso del sistema de gestión de base de datos; y la capacitación de los empleados en la gestión y el uso de las bases de datos. Se espera que un DBA se mantenga al tanto de las nuevas tecnologías y los nuevos enfoques de diseño.

Algunas de sus tareas son las siguientes:
  • Implementar, dar soporte y gestionar bases de datos corporativas.
  • Crear y configurar bases de datos relacionales.
  • Ser responsables de la integridad de los datos y la disponibilidad.
  • Diseñar, desplegar y monitorizar servidores de bases de datos.
  • Diseñar la distribución de los datos y las soluciones de almacenamiento.
  • Garantizar la seguridad de las bases de datos, realizar copias de seguridad y llevar a cabo la recuperación de desastres.
  • Planificar e implementar el aprovisionamiento de los datos y aplicaciones.
  • Diseñar planes de contingencia.
  • Diseñar y crear las bases de datos corporativas de soluciones avanzadas.
  • Analizar y reportar datos corporativos que ayuden a la toma de decisiones en la inteligencia de negocios.
  • Producir diagramas de entidades relacionales y diagramas de flujos de datos, normalización esquemática, localización lógica y física de bases de datos y parámetros de tablas.


1.2 El procesador y sus registros internos

La unidad central de procesamiento o unidad de procesamiento central (central processing unit), es el hardware dentro de un ordenador u otros dispositivos programables, que interpreta las instrucciones de un programa informático mediante la realización de las operaciones básicas aritméticas, lógicas y de entrada/salida del sistema.

Definición de registros: un registro es una memoria de alta velocidad y poca capacidad, integrada en el microprocesador, que permite guardar transitoriamente y acceder a valores muy usados, generalmente en operaciones matemáticas.

Los registros del procesador se emplean para controlar instrucciones en ejecución, manejar direccionamiento de memoria y proporcionar capacidad aritmética. Los registros son direccionables por medio de un nombre.

Tipos de registros

  • Registros de segmento.
  • Registros de propósito general.
  • Registros de apuntadores.
  • Registros de banderas.
  • Registros de Pila.
  • Registros Indice.

 

Registros de segmento

Un registro de segmento tiene 16 bits de longitud y facilita un área de memoria para direccionamiento conocida como el segmento actual.
  • Registro CS:  El DOS almacena la dirección inicial del segmento de código de un programa en el registro CS. Esta dirección de segmento, mas un valor de desplazamiento en el registro apuntador de instrucción (IP), indica la dirección de una instrucción que es buscada para su ejecución.
  • Registro DS:  La dirección inicial de un segmento de datos de programa es almacenada en el registro DS. En términos sencillos, esta dirección, mas un valor de desplazamiento en una instrucción, genera una referencia a la localidad de un byte especifico en el segmento de datos.
  • Registro SS: El registro SS permite la colocación en memoria de una pila, para almacenamiento temporal de direcciones y datos. El DOS almacena la dirección de inicio del segmento de pila de un programa en le registro SS. Esta dirección de segmento, mas un valor de desplazamiento en el registro del apuntador de pila (SP), indica la palabra actual en la pila que esta siendo direccionada.
  • Registros ES: Alguna operaciones con cadenas de caracteres (datos de caracteres) utilizan el registro extra de segmento para manejar el direccionamiento de memoria. En este contexto, el registro ES esta asociado con el registro DI (índice). Un programa que requiere el uso del registro ES puede inicializarlo con una dirección de segmento apropiada.
  • Registros FS y GS:  Son registros extra de segmento en los procesadores 80386 y posteriores.

 

Registros de propósito general

Los registros de propósito general AX, BX, CX y DX son los caballos de batalla del sistema. Son únicos en el sentido de que se puede direccionarlos como una palabra o como una parte de un byte. El ultimo byte de la izquierda es la parte “alta”, y el ultimo byte de la derecha es la parte “baja”. Por ejemplo, el registro CX consta de una parte CH (alta) y una parte Cl (baja), y usted puede referirse a cualquier parte por su nombre.
  • Registro AX:  El registro AX, el acumulador principal, es utilizado para operaciones que implican entrada/salida y la mayor parte de la aritmética. Por ejemplo, las instrucciones para multiplicar , dividir y traducir suponen el uso del AX. También, algunas operaciones generan código mas eficiente si se refieren al AX en lugar de a los otros registros.
  • Registro BX: El BX es conocido como el registro base ya que es el único registro de propósito general que puede ser índice para direccionamiento indexado. También es común emplear el BX para cálculos.
  • Registro DX: Es conocido como el registro de datos. Alguna operaciones de entrada/salida requieren uso, y las operaciones de multiplicación y división con cifras grandes suponen al DX y al AX trabajando juntos.

 

Registros Apuntadores

Los registros SP (apuntador de la pila) Y BP (apuntador de base) están asociados con el registro SS y permiten al sistema accesar datos en el segmento de la pila.
  • Registro SP:  El apuntador de la pila de 16 bits esta asociado con el registro SS y proporciona un valor de desplazamiento que se refiere a la palabra actual que esta siendo procesada en la pila. Los procesadores 80386 y posteriores tienen un apuntador de pila de 32 bits, el registro ESP. El sistema maneja de forma automática estos registros.
  • Registro BP: El BP de 16 bits facilita la referencia de parámetros, los cuales son datos y direcciones transmitidos vía pila. Los procesadores 80386 y posteriores tienen un BP ampliado de 32 bits llamado el registro EBP.

 

Registros Indice

Los registros SI y DI están disponibles para direccionamiento indexado y para sumas y restas.
  • Registro SI: El registro índice fuente de 16 bits es requerido por algunas operaciones con cadenas (de caracteres). En este contexto, el SI esta asociado con el registro DS. Los procesadores 80386 y posteriores permiten el uso de un registro ampliado de 32 bits, el ESI.
  • Registro DI: El registro índice destino también es requerido por algunas operaciones con cadenas de caracteres. En este contexto, el DI esta asociado con el registro ES. Los procesadores 80386 y posteriores permiten el uso de un registro ampliado de 32 bits, el EDI.

 

Registro de Banderas 

De los 16 bits del registro de banderas, nueve son comunes a toda la familia de procesadores 8086, y sirven para indicar el estado actual de la maquina y el resultado del procesamiento. Muchas instrucciones que piden comparaciones y aritmética cambian el estado de las banderas, algunas cuyas instrucciones pueden realizar pruebas para determinar la acción subsecuente. En resumen, los bits de las banderas comunes son como sigue:
  • OF (Overflow, desbordamiento):  Indica desbordamiento de un bit de orden alto (mas a la izquierda) después de una operación aritmética.
  • DF (dirección): Designa la dirección hacia la izquierda o hacia la derecha para mover o comparar cadenas de caracteres.
  • IF (interrupción):  Indica que una interrupción externa, como la entrada desde el teclado, sea procesada o ignorada.
  • TF (trampa): Permite la operación del procesador en modo de un paso. Los programas depuradores, como el DEBUG, activan esta bandera de manera que usted pueda avanzar en la ejecución de una sola instrucción a un tiempo, para examinar el efecto de esa instrucción sobre los registros de memoria.
  • SF (signo): Contiene el signo resultante de una operación aritmética (0 = positivo y 1 = negativo).
  • ZF (cero):  Indica el resultado de una operación aritmética o de comparación (0 = resultado diferente de cero y 1 = resultado igual a cero).
  • AF (acarreo auxiliar): Contiene un acarreo externo del bit 3 en un dato de 8 bits para aritmética especializada.
  • PF  (paridad): Indica paridad par o impar de una operación en datos de 8 bits de bajo orden (mas a la derecha).
  • CF  (acarreo):  Contiene el acarreo de orden mas alto (mas a la izquierda) después de una operación aritmética; también lleva el contenido del ultimo bit en una operación de corrimiento o de rotación. Las banderas están en el registro de banderas en las siguientes posiciones:
Las banderas mas importantes para la programación en ensamblador son O, S, Z y C, para operaciones de comparación y aritméticas, y D para operaciones de cadenas de caracteres. Los procesadores 80286 y posteriores tienen algunas banderas usadas para propósitos internos, en especial las que afectan al modo protegido. Los procesadores 80286 y posteriores tienen un registro extendido de banderas conocido como Eflags.

Registros de PILA

La pila es un área de memoria importante y por ello tiene, en vez de uno, dos registros que se usan como desplazamiento (offset) para apuntar a su contenido. Se usan como complemento al registro y son:
  • SP (Stack Pointer) : Se traduce como puntero de pila y es el que se reserva el procesador para uso propio en instrucciones de manipulado de pila. Por lo general , el programador no debe alterar su contenido.
  • BP  (Base pointer):  Se usa como registro auxiliar. El programador puede usarlo para su provecho.



1.1 Importancia de la programación en lenguaje ensamblador

El lenguaje  ensamblador es  un  tipo  de  lenguaje  de  bajo  nivel  utilizado para  escribir programas  informáticos,  y  constituye  la  representación  más  directa del código máquina específico para cada arquitectura de microprocesador.

Consiste en un conjunto de mnemónicos que representan instrucciones básicas para los computadores, microprocesadores, microcontroladores y otros circuitos integrados programables.

Características

  • Posee una cierta dificultad de ser entendido ya que su estructura se acerca al lenguaje máquina, es decir, es un lenguaje de bajo nivel.
  • Es difícilmente portable, es decir, un código escrito para un microprocesador, puede necesitar ser modificado, para poder ser usado en otra máquina distinta. Al cambiar a una máquina con arquitectura diferente, generalmente es necesario reescribirlo completamente.
  • Los programas hechos por un programador experto en lenguaje ensamblador son generalmente mucho más rápidos y consumen menos recursos del sistema (memoria RAM y ROM) que el programa equivalente compilado desde un lenguaje de alto nivel. Al programar cuidadosamente en lenguaje ensamblador se pueden crear programas que se ejecutan más rápidamente y ocupan menos espacio que con lenguajes de alto nivel.
  • Con el lenguaje ensamblador se tiene un control muy preciso de las tareas realizadas por un microprocesador por lo que se pueden crear segmentos de código difíciles y/o muy ineficientes de programar en un lenguaje de alto nivel, ya que, entre otras cosas, en el lenguaje ensamblador se dispone de instrucciones del CPU que generalmente no están disponibles en los lenguajes de alto nivel.

 

Importancia del lenguaje ensamblador

La importancia del lenguaje ensamblador radica principalmente que se trabaja directamente con el microprocesador; por lo cual se debe de conocer el funcionamiento interno de este, tiene la ventaja de que en el se puede realizar cualquier tipo de programas que en los lenguajes de alto nivel no lo pueden realizar. Otro punto sería que los programas en ensamblador ocupan menos espacio en memoria.

Ventajas

  • Menor consumo de recursos.
  • Velocidad de ejecución de los programas.
  • Mayor control sobre el hardware. 

Desventajas

  • Mayor tiempo de programación y cantidad de código.
  • Dificultad para encontrar errores en los programas.
  • Falta de portabilidad.
  • Peligro de afectar recursos inesperadamente.

martes, 14 de noviembre de 2017

Esferas 3D


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Librerías del programa
import sys
import math
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *


# Iluminación personalizada de la animación
class Luz(object):
    encendida = True
    colores = [(1., 1., 1., 1.), (1., 0.5, 0.5, 1.),
               (0.5,1.,0.5,1.), (0.5,0.5,1.,1.)]
    def __init__(self, luz_id, posicion):
        # Identificador del objeto de iluminación
        self.luz_id = luz_id
        # Posición de la iluminación
        self.posicion = posicion
        # Variable para seleccionar colores
        self.color_actual = 0

    # Tipo de iluminación
    def dibujar(self):
        light_id = self.luz_id
        color = Luz.colores[self.color_actual]
        glLightfv(light_id, GL_POSITION, self.posicion)
        glLightfv(light_id, GL_DIFFUSE, color)
        glLightfv(light_id, GL_CONSTANT_ATTENUATION, 0.1)
        glLightfv(light_id, GL_LINEAR_ATTENUATION, 0.05)

    def cambiar_color(self):
        self.color_actual += 1
        # Reinicia el color actual
        self.color_actual %= len(Luz.colores)


    def enable(self):
        if not Luz.encendida:
            glEnable(GL_LIGHTING)
            Luz.encendida = True
        glEnable(self.luz_id)

# Construcción de la Esfera
class Esfera(object):
    # Divisiones de norte a sur
    meridianos = 40
    # Divisiones este a oeste
    paralelos = 40

    # Constructor de la clase
    def __init__(self, radio, posicion, color):
        self.radio = radio
        self.posicion = posicion
        self.color = color

    # Función que dibuja una esfera
    def dibujar(self):
        # Ubicacion de la figura 3d
        glTranslatef(*self.posicion)
        # Especifica los parametros del material para la iluminación
        # GL_AMBIENT , GL_EMISSION
        glMaterialfv(GL_FRONT, GL_DIFFUSE, self.color)
        # Función especial para dibujar esferas
        glutSolidSphere(self.radio, Esfera.meridianos, Esfera.paralelos)

# Aplicación principal
class App(object):
    # Constructor de la clase
    def __init__(self, largo=800, ancho=600):
        # Titulo de la ventana
        self.titulo = 'Esferas con OpenGL'
        # Medidas de la ventana
        self.largo = largo
        self.ancho = ancho
        # Angulo de vision de la camara
        self.angulo = 0
        # Distancia de la camara
        self.distancia = 20
        # Instancia de la clase Luz
        self.iluminacion = Luz(GL_LIGHT0, (15, 5, 15, 1))
        # Instancia de la clase Esfera
        self.esfera1 = Esfera(2, (0, 0, 0), (1, 1, 1, 1))
        # Instancia de la clase Esfera
        self.esfera2 = Esfera(1, (4, 2, 0), (1, 0.4, 0.4, 1))

    # Función que crea la ventana y los graficos 3d
    def iniciar(self):
        # Inicializa la librería GLUT
        glutInit()

        # Funciones para inicializar la ventana
        glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH)
        glutInitWindowPosition(50, 50)
        glutInitWindowSize(self.largo, self.ancho)
        glutCreateWindow(self.titulo)

        # Activar las funciones graficas
        glEnable(GL_DEPTH_TEST)
        # Activar iluminación
        glEnable(GL_LIGHTING)
        # Seleccionar la constante de iluminación
        glEnable(GL_LIGHT0)

        # Activar la iluminación con las características de nuestra función
        self.iluminacion.enable()

        # Color de fondo
        glClearColor(.1, .1, .1, 1)

        glMatrixMode(GL_PROJECTION)
        aspect = self.largo / self.ancho
        gluPerspective(40., aspect, 1., 40.)
        glMatrixMode(GL_MODELVIEW)

        # Llamada para dibujar las figuras
        glutDisplayFunc(self.dibujar)
        # Llamada para activar las funciones del teclado
        glutSpecialFunc(self.keyboard)

        #Inicia el ciclo de la libreria
        glutMainLoop()
        # ...

    # Función que dibuja las figuras 3D
    def dibujar(self):
        # Coordenadas de la cámara
        x = math.sin(self.angulo) * self.distancia
        z = math.cos(self.angulo) * self.distancia

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glLoadIdentity()

        # Coordenadas de la cámara
        # Posición
        # Dirección en la que mira
        # Orientación
        gluLookAt(x, 0, z,
                  0, 0, 0,
                  0, 1, 0)

        # Se crea la iluminación
        self.iluminacion.dibujar()

        # Se crea la primer esfera
        self.esfera1.dibujar()
        # Se crea la segunda esfera
        self.esfera2.dibujar()

        glutSwapBuffers()

    # Funciones del teclado
    def keyboard(self, tecla, x, y):
        if tecla == GLUT_KEY_INSERT:
            # Cerrar ventana
            sys.exit()
        if tecla == GLUT_KEY_UP:
            # Acercar la cámara
            self.distancia -= 0.1
        if tecla == GLUT_KEY_DOWN:
            # Alejar cámara
            self.distancia += 0.1
        if tecla == GLUT_KEY_LEFT:
            # Girar cámara a la izquierda
            self.angulo -= 0.05
        if tecla == GLUT_KEY_RIGHT:
            # Girar cámara a la derecha
            self.angulo += 0.05
        if tecla == GLUT_KEY_F1:
            # Cambiar color de las esferas
            self.iluminacion.cambiar_color()
        # Máxima y mínima distancia de la cámara
        self.distancia = max(10, min(self.distancia, 20))
        # Reiniciar el ángulo de giro
        self.angulo %= math.pi * 2
        # Actualiza el plano 3d y las figuras de acuerdo al movimiento de la camara
        glutPostRedisplay()


if __name__ == '__main__':
    app = App()
    app.iniciar()



https://drive.google.com/file/d/1g01y1-6-TQJOzCVfgJfw6wGtfKfa4KoH/view?usp=sharing


lunes, 13 de noviembre de 2017

Gráfico de barras 3D

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')

xpos = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
ypos = [2,3,4,5,1,6,2,1,7,2,3,5,1,3,2]
num_elements = len(xpos)
zpos = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
dx = np.ones(15)
dy = np.ones(15)
dz = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

ax1.bar3d(xpos, ypos, zpos, dx, dy, dz, color='#00ceaa')
plt.show()

miércoles, 8 de noviembre de 2017

Practica python 3D - Cubo con colores


import sys, math, pygame
from operator import itemgetter


class Point3D:
    def __init__(self, x=0, y=0, z=0):
        self.x, self.y, self.z = float(x), float(y), float(z)

    def rotateX(self, angle):
        """ Rotates the point around the X axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        y = self.y * cosa - self.z * sina
        z = self.y * sina + self.z * cosa
        return Point3D(self.x, y, z)

    def rotateY(self, angle):
        """ Rotates the point around the Y axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        z = self.z * cosa - self.x * sina
        x = self.z * sina + self.x * cosa
        return Point3D(x, self.y, z)

    def rotateZ(self, angle):
        """ Rotates the point around the Z axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        x = self.x * cosa - self.y * sina
        y = self.x * sina + self.y * cosa
        return Point3D(x, y, self.z)

    def project(self, win_width, win_height, fov, viewer_distance):
        """ Transforms this 3D point to 2D using a perspective projection. """
        factor = fov / (viewer_distance + self.z)
        x = self.x * factor + win_width / 2
        y = -self.y * factor + win_height / 2
        return Point3D(x, y, self.z)


class Simulation:
    def __init__(self, win_width=640, win_height=480):
        pygame.init()

        self.screen = pygame.display.set_mode((win_width, win_height))
        pygame.display.set_caption("Figura de cubo 3D en python")

        self.clock = pygame.time.Clock()

        self.vertices = [
            Point3D(-1, 1, -1),
            Point3D(1, 1, -1),
            Point3D(1, -1, -1),
            Point3D(-1, -1, -1),
            Point3D(-1, 1, 1),
            Point3D(1, 1, 1),
            Point3D(1, -1, 1),
            Point3D(-1, -1, 1)
        ]

        # Define the vertices that compose each of the 6 faces. These numbers are
        # indices to the vertices list defined above.
        self.faces = [(0, 1, 2, 3), (1, 5, 6, 2), (5, 4, 7, 6), (4, 0, 3, 7), (0, 4, 5, 1), (3, 2, 6, 7)]

        # Define colors for each face
        self.colors = [(255, 0, 255), (255, 0, 0), (0, 255, 0), (0, 0, 255), (0, 255, 255), (255, 255, 0)]

        self.angle = 0

    def run(self):
        """ Main Loop """
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            self.clock.tick(50)
            self.screen.fill((0, 32, 0))

            # It will hold transformed vertices.
            t = []

            for v in self.vertices:
                # Rotate the point around X axis, then around Y axis, and finally around Z axis.
                r = v.rotateX(self.angle).rotateY(self.angle).rotateZ(self.angle)
                # Transform the point from 3D to 2D
                p = r.project(self.screen.get_width(), self.screen.get_height(), 256, 4)
                # Put the point in the list of transformed vertices
                t.append(p)

            # Calculate the average Z values of each face.
            avg_z = []
            i = 0
            for f in self.faces:
                z = (t[f[0]].z + t[f[1]].z + t[f[2]].z + t[f[3]].z) / 4.0
                avg_z.append([i, z])
                i = i + 1

            # Draw the faces using the Painter's algorithm:
            # Distant faces are drawn before the closer ones.
            for tmp in sorted(avg_z, key=itemgetter(1), reverse=True):
                face_index = tmp[0]
                f = self.faces[face_index]
                pointlist = [(t[f[0]].x, t[f[0]].y), (t[f[1]].x, t[f[1]].y),
                             (t[f[1]].x, t[f[1]].y), (t[f[2]].x, t[f[2]].y),
                             (t[f[2]].x, t[f[2]].y), (t[f[3]].x, t[f[3]].y),
                             (t[f[3]].x, t[f[3]].y), (t[f[0]].x, t[f[0]].y)]
                pygame.draw.polygon(self.screen, self.colors[face_index], pointlist)

            self.angle += 1

            pygame.display.flip()


if __name__ == "__main__":
    Simulation().run()


       
import sys, math, pygame
from operator import itemgetter


class Point3D:
    def __init__(self, x=0, y=0, z=0):
        self.x, self.y, self.z = float(x), float(y), float(z)

    def rotateX(self, angle):
        """ Rotates the point around the X axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        y = self.y * cosa - self.z * sina
        z = self.y * sina + self.z * cosa
        return Point3D(self.x, y, z)

    def rotateY(self, angle):
        """ Rotates the point around the Y axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        z = self.z * cosa - self.x * sina
        x = self.z * sina + self.x * cosa
        return Point3D(x, self.y, z)

    def rotateZ(self, angle):
        """ Rotates the point around the Z axis by the given angle in degrees. """
        rad = angle * math.pi / 180
        cosa = math.cos(rad)
        sina = math.sin(rad)
        x = self.x * cosa - self.y * sina
        y = self.x * sina + self.y * cosa
        return Point3D(x, y, self.z)

    def project(self, win_width, win_height, fov, viewer_distance):
        """ Transforms this 3D point to 2D using a perspective projection. """
        factor = fov / (viewer_distance + self.z)
        x = self.x * factor + win_width / 2
        y = -self.y * factor + win_height / 2
        return Point3D(x, y, self.z)


class Simulation:
    def __init__(self, win_width=640, win_height=480):
        pygame.init()

        self.screen = pygame.display.set_mode((win_width, win_height))
        pygame.display.set_caption("Figura de cubo 3D en python")

        self.clock = pygame.time.Clock()

        self.vertices = [
            Point3D(-1, 1, -1),
            Point3D(1, 1, -1),
            Point3D(1, -1, -1),
            Point3D(-1, -1, -1),
            Point3D(-1, 1, 1),
            Point3D(1, 1, 1),
            Point3D(1, -1, 1),
            Point3D(-1, -1, 1)
        ]

        # Define the vertices that compose each of the 6 faces. These numbers are
        # indices to the vertices list defined above.
        self.faces = [(0, 1, 2, 3), (1, 5, 6, 2), (5, 4, 7, 6), (4, 0, 3, 7), (0, 4, 5, 1), (3, 2, 6, 7)]

        # Define colors for each face
        self.colors = [(1, 172, 226), (73, 23, 110), (146, 39, 143), (121, 85, 72), (171, 5, 53), (255, 255, 0)]

        self.angle = 0

    def run(self):
        """ Main Loop """
        while 1:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    sys.exit()

            self.clock.tick(50)
            self.screen.fill((0, 32, 0))

            # It will hold transformed vertices.
            t = []

            for v in self.vertices:
                # Rotate the point around X axis, then around Y axis, and finally around Z axis.
                r = v.rotateX(self.angle).rotateY(self.angle).rotateZ(self.angle)
                # Transform the point from 3D to 2D
                p = r.project(self.screen.get_width(), self.screen.get_height(), 256, 4)
                # Put the point in the list of transformed vertices
                t.append(p)

            # Calculate the average Z values of each face.
            avg_z = []
            i = 0
            for f in self.faces:
                z = (t[f[0]].z + t[f[1]].z + t[f[2]].z + t[f[3]].z) / 4.0
                avg_z.append([i, z])
                i = i + 1

            # Draw the faces using the Painter's algorithm:
            # Distant faces are drawn before the closer ones.
            for tmp in sorted(avg_z, key=itemgetter(1), reverse=True):
                face_index = tmp[0]
                f = self.faces[face_index]
                pointlist = [(t[f[0]].x, t[f[0]].y), (t[f[1]].x, t[f[1]].y),
                             (t[f[1]].x, t[f[1]].y), (t[f[2]].x, t[f[2]].y),
                             (t[f[2]].x, t[f[2]].y), (t[f[3]].x, t[f[3]].y),
                             (t[f[3]].x, t[f[3]].y), (t[f[0]].x, t[f[0]].y)]
                pygame.draw.polygon(self.screen, self.colors[face_index], pointlist)

            self.angle += 1

            pygame.display.flip()


if __name__ == "__main__":
    Simulation().run()

Practica python 3D - Cubo y piramide

import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()


def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

    glTranslatef(0.0,0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)


main()


import pygame
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *

verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    ( 0,  0,  1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (4,1),
    (4,2),
    (4,3)
    )


def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()


def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)

    gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)

    glTranslatef(0.0,0.0, -5)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        glRotatef(1, 3, 1, 1)
        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)


main()


lunes, 30 de octubre de 2017

Figuras 3D en Python

https://www.youtube.com/watch?v=R4n4NyDG2hI

Progarama de figuras con Turtle

# -*- coding: utf-8 -*-
from Tkinter import *
import turtle
import tkSimpleDialog
from tkColorChooser import askcolor
import math

ventanaPrincipal = Tk()
ventanaPrincipal.resizable(False, False)
ventanaPrincipal.title("Ventana principal - Area de dibujo")

canvasLienzo = Canvas(ventanaPrincipal, width=750, height=750)
canvasLienzo.pack(side="left", fill="both", expand=True)

canvasMenu = Canvas(ventanaPrincipal, width=750, height=750)
canvasMenu.pack(side="right", fill="both", expand=True)

turtle_screen = turtle.TurtleScreen(canvasLienzo)
turtle_screen.bgcolor("white")
tortuga=turtle.RawTurtle(turtle_screen)

lapizColor = "black"
rellenoColor = "white"
tortuga.fill(False)
fondoColor = "white"

posicionX=DoubleVar()
posicionY=DoubleVar()

def limpiar():
    tortuga.reset()
    colorLapiz(botonLapiz,"black")
    colorRelleno(botonRelleno,"white")
    colorFondo(botonFondo,"white")

def colorLapiz(self,color):
    self.configure(bg = color)
    tortuga.pencolor(color)

def colorRelleno(self,color):
    self.configure(bg=color)
    tortuga.fill(True)
    print tortuga.fill()
    tortuga.fillcolor(color)

def colorFondo(self,color):
    self.configure(bg=color)
    turtle_screen.bgcolor(color)

def seleccionarColor():
    seleccion = askcolor()
    return seleccion[1]

def tamanioLapiz(event):
    w=event.widget
    if isinstance(w,Scale):
        tortuga.pensize(w.get())

def cambiarCoordenadas():
    try:
        posicionX.set(tkSimpleDialog.askfloat("Posición en X", "Ingresa la coordenada: ", initialvalue=0.0))
        posicionY.set(tkSimpleDialog.askfloat("Posición en Y", "Ingresa la coordenada: ", initialvalue=0.0))
        tortuga.penup()
        tortuga.goto(posicionX.get(),posicionY.get())
        tortuga.pendown()
    except:
        print "Operación cancelada"

def poligono():
    try:
        lados = tkSimpleDialog.askinteger("Poligono regular", "Ingresa el número de lados: ",initialvalue=3,minvalue=3,maxvalue=360)
        linea = tkSimpleDialog.askinteger("Poligono regular", "Ingresa el tamaño de cada lado: ", initialvalue=50,minvalue=1)
        angulo = DoubleVar()
        angulo.set(360.0/lados)
        print tortuga.fill()
        if(tortuga.fill()==True):
            tortuga.begin_fill()
        for i in range(lados):
            tortuga.forward(linea)
            tortuga.left(angulo.get())
        tortuga.end_fill()
        colorRelleno(botonRelleno,"white")
        tortuga.fill(False)
    except:
        print "Operacion cancelada"

def mariposa():
    n = 0
    colores = ["#201815", "#584C4C", "#3F6E80", "#0F4851", "#473A68", "#201815", "#584C4C", "#3F6E80", "#0F4851",
               "#473A68"]
    if (tortuga.fill() == True):
        tortuga.begin_fill()
    for t in range(0, 3600):
        if (t % 360 == 0):
            tortuga.pencolor(colores[n])
            colorLapiz(botonLapiz, colores[n])
            n = n + 1
        t = t * ((math.pi) / 180)
        x = (math.sin(t) * ((math.exp(math.cos(t))) - (2 * math.cos(4 * t)) - ((math.sin(t / 12)) ** 5))) * 60
        y = (math.cos(t) * ((math.exp(math.cos(t))) - (2 * math.cos(4 * t)) - ((math.sin(t / 12)) ** 5))) * 60
        tortuga.goto(x, y)
    tortuga.end_fill()

def repetirPoligonos():
    try:
        lados = tkSimpleDialog.askinteger("Poligono regular", "Ingresa el número de lados: ",initialvalue=3,minvalue=3,maxvalue=360)
        linea = tkSimpleDialog.askinteger("Poligono regular", "Ingresa el tamaño de cada lado: ", initialvalue=50,minvalue=1)
        repeticion = tkSimpleDialog.askinteger("Poligono regular", "Ingresa el número de repeticiones: ", initialvalue=1,minvalue=1, maxvalue=100)
        angulo = tkSimpleDialog.askinteger("Poligono regular", "Ingresa el ángulo de rotación: ",initialvalue=1, minvalue=1, maxvalue=360)

        anguloFigura = DoubleVar()
        anguloFigura.set(360.0/lados)
        print tortuga.fill()

        if (tortuga.fill() == True):
            tortuga.begin_fill()
        for i in range(repeticion):
            tortuga.left(angulo)
            for j in range(lados):
                tortuga.forward(linea)
                tortuga.left(anguloFigura.get())
        tortuga.end_fill()
        colorRelleno(botonRelleno,"white")
        tortuga.fill(False)
    except:
        print "Operacion cancelada"

def espiral():
    tam=25
    tortuga.speed(20)
    for i in range(120):
        tortuga.left(5)
        for j in range(4):
            tortuga.forward(tam)
            tortuga.left(90)
        tam=tam+5

def origen():
    tortuga.penup()
    tortuga.home()
    tortuga.pendown()

def globo():
    aumento = 0
    aumento2=0
    color = ["#c1133d", "#e2e2e2", "#842a40"]
    for i in range(3):
        tortuga.penup()
        tortuga.home()
        tortuga.pendown()

        colorRelleno(botonRelleno,color[i])
        tortuga.fillcolor(color[i])
        tortuga.begin_fill()
        tortuga.forward(30 - aumento)
        tortuga.left(50 + aumento)
        tortuga.forward(120)
        tortuga.left(5)
        tortuga.forward(30)
        tortuga.left(5)
        tortuga.forward(30)
        tortuga.left(5)
        tortuga.forward(30)

        if (i == 2):
            tortuga.left(2)
            tortuga.forward(15)
            tortuga.left(2)
            tortuga.forward(15)
            tortuga.left(2)
            tortuga.forward(15)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(4)
            tortuga.forward(10)
            tortuga.left(4)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.home()
            tortuga.end_fill()
        if (i == 1):
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(15)
            tortuga.forward(15)

            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(3)
            tortuga.forward(10)
            tortuga.left(2)
            tortuga.forward(10)
            tortuga.left(2)
            tortuga.forward(12)
            tortuga.home()
            tortuga.end_fill()
        if (i == 0):
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(10)
            tortuga.forward(30)
            tortuga.left(15)
            tortuga.forward(15)

            tortuga.left(5)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(10)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)
            tortuga.left(5)
            tortuga.forward(15)

            tortuga.end_fill()

        aumento += 10

    for i in range(3):
        tortuga.penup()
        tortuga.home()
        tortuga.pendown()

        colorRelleno(botonRelleno, color[2 - i])
        tortuga.fillcolor(color[2 - i])
        tortuga.begin_fill()

        tortuga.left(180)
        tortuga.forward(30 - aumento2)
        tortuga.right(50 + aumento2)
        tortuga.forward(120)
        tortuga.right(5)
        tortuga.forward(30)
        tortuga.right(5)
        tortuga.forward(30)
        tortuga.right(5)
        tortuga.forward(30)

        if (i == 2):
            tortuga.right(2)
            tortuga.forward(15)
            tortuga.right(2)
            tortuga.forward(15)
            tortuga.right(2)
            tortuga.forward(15)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(4)
            tortuga.forward(10)
            tortuga.right(4)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)

            tortuga.end_fill()
        if (i == 1):
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(15)
            tortuga.forward(14)

            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(3)
            tortuga.forward(10)
            tortuga.right(2)
            tortuga.forward(10)
            tortuga.right(2)
            tortuga.forward(12)

            tortuga.end_fill()
        if (i == 0):
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(10)
            tortuga.forward(30)
            tortuga.right(15)
            tortuga.forward(14)

            tortuga.right(5)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(10)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)
            tortuga.right(5)
            tortuga.forward(15)

            tortuga.end_fill()

        aumento2 += 10

    origen()
    tortuga.goto(2, 373)

    origen()
    colorRelleno(botonRelleno, "#A05150")
    tortuga.fillcolor("#A05150")
    tortuga.begin_fill()
    tortuga.forward(30)
    tortuga.right(120)
    tortuga.forward(15)
    tortuga.right(60)
    tortuga.forward(46)
    tortuga.right(60)
    tortuga.forward(15)
    tortuga.home()
    tortuga.end_fill()

    tortuga.penup()
    tortuga.goto(16, -12)
    tortuga.pensize(3)
    tortuga.pendown()
    tortuga.right(90)
    tortuga.forward(20)
    tortuga.left(160)
    tortuga.forward(20)

    origen()
    tortuga.penup()
    tortuga.goto(-15, -12)
    tortuga.pendown()
    tortuga.right(90)
    tortuga.forward(20)
    tortuga.right(155)
    tortuga.forward(20)

    origen()
    tortuga.penup()
    tortuga.goto(0, -32)
    tortuga.pendown()
    colorLapiz(botonLapiz, "#C96B46")
    tortuga.pencolor("#C96B46")
    tortuga.pensize(4)
    tortuga.forward(15)
    tortuga.right(65)
    tortuga.forward(30)

    origen()
    tortuga.penup()
    tortuga.goto(0, -32)
    tortuga.pendown()
    tortuga.right(180)
    tortuga.forward(15)
    tortuga.left(65)
    tortuga.forward(30)

    origen()
    tortuga.penup()
    tortuga.goto(0, -60)
    tortuga.pendown()
    colorLapiz(botonLapiz, "#000000")
    tortuga.pencolor("#000000")
    colorRelleno(botonRelleno, "#A05150")
    tortuga.fillcolor("#A05150")
    tortuga.begin_fill()
    tortuga.pensize(2)
    tortuga.forward(35)
    tortuga.right(90)
    tortuga.forward(6)
    tortuga.right(90)
    tortuga.forward(70)
    tortuga.right(90)
    tortuga.forward(6)
    tortuga.right(90)
    tortuga.forward(35)
    tortuga.end_fill()

    tortuga.penup()
    tortuga.right(90)
    tortuga.forward(6)
    tortuga.pendown()
    colorRelleno(botonRelleno, "#8D3E35")
    tortuga.fillcolor("#8D3E35")
    tortuga.begin_fill()
    tortuga.left(90)
    tortuga.forward(33)
    tortuga.right(110)
    tortuga.forward(30)
    tortuga.right(70)
    tortuga.forward(45)
    tortuga.right(70)
    tortuga.forward(30)
    tortuga.right(110)
    tortuga.forward(33)
    tortuga.end_fill()


etiquetaT1 = Label(canvasMenu, text="Opciones", justify=CENTER, font="Arial 12")
etiquetaT1.grid(row=1, column=1,columnspan=2)

etiquetaT1 = Label(canvasMenu, text="Lápiz:", font="Arial 10", pady=5)
etiquetaT1.grid(row=2, column=1)

botonLapiz = Button(canvasMenu, bg=lapizColor, command=lambda: colorLapiz(botonLapiz, seleccionarColor()))
botonLapiz.grid(row=2, column=2, sticky="W,E")

etiquetaT2 = Label(canvasMenu, text="Relleno:", font="Arial 10", pady=5)
etiquetaT2.grid(row=3, column=1)

botonRelleno = Button(canvasMenu, bg=rellenoColor, command=lambda: colorRelleno(botonRelleno, seleccionarColor()))
botonRelleno.grid(row=3, column=2, sticky="W,E")

etiquetaT3 = Label(canvasMenu, text="Fondo:", font="Arial 10", pady=5)
etiquetaT3.grid(row=4, column=1)

botonFondo = Button(canvasMenu, bg=fondoColor, command=lambda: colorFondo(botonFondo, seleccionarColor()))
botonFondo.grid(row=4, column=2, sticky="W,E")

etiquetaT4 = Label(canvasMenu, text="Tamaño del lápiz", font="Arial 10", pady=5)
etiquetaT4.grid(row=5, column=1,columnspan=2)

botonEscala = Scale(canvasMenu, orient=HORIZONTAL, from_=1, to=10)
botonEscala.grid(row=6, column=1, sticky="W,E",columnspan=2)
botonEscala.bind('',tamanioLapiz)

botonPoligonos = Button(canvasMenu,text="Poligono regular",command=lambda: poligono())
botonPoligonos.grid(row=7, column=1, sticky="W,E", columnspan=2)

botonRepetir = Button(canvasMenu, text="Repetir Poligonos",command=lambda:repetirPoligonos())
botonRepetir.grid(row=8, column=1, sticky="W,E", columnspan=2)

botonMover = Button(canvasMenu, text="Cambiar coordenadas", command=lambda: cambiarCoordenadas())
botonMover.grid(row=9, column=1, sticky="W,E", columnspan=2,pady=10)

botonGlobo = Button(canvasMenu, text="Dibujo globo", command=lambda: globo())
botonGlobo.grid(row=10, column=1, sticky="W,E", columnspan=2)

botonMariposa = Button(canvasMenu, text="Mariposa", command=lambda: mariposa())
botonMariposa.grid(row=11, column=1, sticky="W,E", columnspan=2)

botonMariposa = Button(canvasMenu, text="Espiral", command=lambda: espiral())
botonMariposa.grid(row=12, column=1, sticky="W,E", columnspan=2)


botonLimpiar = Button(canvasMenu, text="Limpiar lienzo", command=lambda: limpiar())
botonLimpiar.grid(row=19, column=1, sticky="W,E", columnspan=2,pady=10)

mainloop()

jueves, 19 de octubre de 2017

Figura propia con turtle

import turtle

n = turtle.Turtle()
turtle.setup(800, 800, 0, 0)
turtle.screensize(750,750)
turtle.bgcolor("#7FBFB1")
n.pensize(2)
n.speed(10)

aumento=0
aumento2=0
color=["#c1133d","#e2e2e2","#842a40"]

def origen():
    n.penup()
    n.home()
    n.pendown()

for i in range(3):
    n.penup()
    n.home()
    n.pendown()

    n.fillcolor(color[i])
    n.begin_fill()
    n.forward(30 - aumento)
    n.left(50 + aumento)
    n.forward(120)
    n.left(5)
    n.forward(30)
    n.left(5)
    n.forward(30)
    n.left(5)
    n.forward(30)

    if(i==2):
        n.left(2)
        n.forward(15)
        n.left(2)
        n.forward(15)
        n.left(2)
        n.forward(15)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(4)
        n.forward(10)
        n.left(4)
        n.forward(10)
        n.left(5)
        n.forward(10)
        n.left(5)
        n.forward(10)
        n.left(5)
        n.forward(10)
        n.left(5)
        n.forward(10)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.home()
        n.end_fill()
    if(i==1):
        n.left(10)
        n.forward(30)
        n.left(10)
        n.forward(30)
        n.left(10)
        n.forward(30)
        n.left(10)
        n.forward(30)
        n.left(15)
        n.forward(15)

        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(3)
        n.forward(10)
        n.left(2)
        n.forward(10)
        n.left(2)
        n.forward(12)
        n.home()
        n.end_fill()
    if(i==0):
        n.left(10)
        n.forward(30)
        n.left(10)
        n.forward(30)
        n.left(10)
        n.forward(30)
        n.left(10)
        n.forward(30)
        n.left(15)
        n.forward(15)

        n.left(5)
        n.forward(10)
        n.left(5)
        n.forward(10)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)
        n.left(5)
        n.forward(15)

        n.end_fill()



    aumento+=10

for i in range(3):
    n.penup()
    n.home()
    n.pendown()

    n.fillcolor(color[2-i])
    n.begin_fill()

    n.left(180)
    n.forward(30 - aumento2)
    n.right(50 + aumento2)
    n.forward(120)
    n.right(5)
    n.forward(30)
    n.right(5)
    n.forward(30)
    n.right(5)
    n.forward(30)

    if (i == 2):
        n.right(2)
        n.forward(15)
        n.right(2)
        n.forward(15)
        n.right(2)
        n.forward(15)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(4)
        n.forward(10)
        n.right(4)
        n.forward(10)
        n.right(5)
        n.forward(10)
        n.right(5)
        n.forward(10)
        n.right(5)
        n.forward(10)
        n.right(5)
        n.forward(10)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)

        n.end_fill()
    if (i == 1):
        n.right(10)
        n.forward(30)
        n.right(10)
        n.forward(30)
        n.right(10)
        n.forward(30)
        n.right(10)
        n.forward(30)
        n.right(15)
        n.forward(14)

        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(3)
        n.forward(10)
        n.right(2)
        n.forward(10)
        n.right(2)
        n.forward(12)

        n.end_fill()
    if (i == 0):
        n.right(10)
        n.forward(30)
        n.right(10)
        n.forward(30)
        n.right(10)
        n.forward(30)
        n.right(10)
        n.forward(30)
        n.right(15)
        n.forward(14)

        n.right(5)
        n.forward(10)
        n.right(5)
        n.forward(10)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)
        n.right(5)
        n.forward(15)

        n.end_fill()

    aumento2 += 10

origen()
n.goto(2,373)

origen()
n.fillcolor("#A05150")
n.begin_fill()
n.forward(30)
n.right(120)
n.forward(15)
n.right(60)
n.forward(46)
n.right(60)
n.forward(15)
n.home()
n.end_fill()



n.penup()
n.goto(16,-12)
n.pensize(3)
n.pendown()
n.right(90)
n.forward(20)
n.left(160)
n.forward(20)

origen()
n.penup()
n.goto(-15,-12)
n.pendown()
n.right(90)
n.forward(20)
n.right(155)
n.forward(20)



origen()
n.penup()
n.goto(0,-32)
n.pendown()
n.pencolor("#C96B46")
n.pensize(4)
n.forward(15)
n.right(65)
n.forward(30)

origen()
n.penup()
n.goto(0,-32)
n.pendown()
n.right(180)
n.forward(15)
n.left(65)
n.forward(30)


origen()
n.penup()
n.goto(0,-60)
n.pendown()
n.pencolor("#000000")
n.fillcolor("#A05150")
n.begin_fill()
n.pensize(2)
n.forward(35)
n.right(90)
n.forward(6)
n.right(90)
n.forward(70)
n.right(90)
n.forward(6)
n.right(90)
n.forward(35)
n.end_fill()

n.penup()
n.right(90)
n.forward(6)
n.pendown()
n.fillcolor("#8D3E35")
n.begin_fill()
n.left(90)
n.forward(33)
n.right(110)
n.forward(30)
n.right(70)
n.forward(45)
n.right(70)
n.forward(30)
n.right(110)
n.forward(33)
n.end_fill()


n.hideturtle()
turtle.done()

miércoles, 18 de octubre de 2017

Figuras con librería Turtle (ventanas de diálogo)

1. Triángulo
import turtle
import tkSimpleDialog
turtle.speed(1)

turtle.pensize(2)
fondo=tkSimpleDialog.askstring("Ingresar color","Escribe el color del fondo:")
lapiz=tkSimpleDialog.askstring("Ingresar color","Escribe el color del lapiz:")
relleno=tkSimpleDialog.askstring("Ingresar color","Escribe el color del relleno:")
turtle.bgcolor(fondo)
turtle.color(lapiz,relleno)

turtle.begin_fill()
for i in range(3):
    turtle.forward(150)
    turtle.left(120)
turtle.end_fill()

turtle.done()

2. Hexágono
import turtle
import tkSimpleDialog
turtle.speed(1)

turtle.pensize(2)
fondo=tkSimpleDialog.askstring("Ingresar color","Escribe el color del fondo:")
lapiz=tkSimpleDialog.askstring("Ingresar color","Escribe el color del lapiz:")
relleno=tkSimpleDialog.askstring("Ingresar color","Escribe el color del relleno:")
turtle.bgcolor(fondo)
turtle.color(lapiz,relleno)

turtle.begin_fill()
for i in range(6):
    turtle.forward(100)
    turtle.left(60)
turtle.end_fill()

turtle.done()

3. Octágono
import turtle
import tkSimpleDialog
turtle.speed(1)

turtle.pensize(2)
fondo=tkSimpleDialog.askstring("Ingresar color","Escribe el color del fondo:")
lapiz=tkSimpleDialog.askstring("Ingresar color","Escribe el color del lapiz:")
relleno=tkSimpleDialog.askstring("Ingresar color","Escribe el color del relleno:")
turtle.bgcolor(fondo)
turtle.color(lapiz,relleno)

turtle.begin_fill()
for i in range(8):
    turtle.forward(100)
    turtle.left(45)
turtle.end_fill()

turtle.done()


martes, 17 de octubre de 2017

Figuras con turtle utilizando el ciclo for

1. Rectángulo
import turtle

turtle.speed(1)

fondo = turtle.Screen()
fondo.bgcolor("yellow")

for i in range(4):
    turtle.forward(100)
    turtle.right(90)

turtle.done()


import turtle

turtle.speed(1)

fondo = turtle.Screen()
fondo.bgcolor("yellow")

for i in range(4):
    turtle.forward(100)
    turtle.right(90)
    for j in range(1):
        turtle.forward(100)
        turtle.right(80)

turtle.done()


import turtle

turtle.speed(10)

fondo = turtle.Screen()
fondo.bgcolor("yellow")

for i in range(40):
    turtle.forward(100)
    turtle.right(90)
    for j in range(1):
        turtle.forward(100)
        turtle.right(80)

turtle.done()


2. Triángulo
import turtle

turtle.speed(1)

fondo = turtle.Screen()
fondo.bgcolor("gray")
turtle.pensize(2)

for i in range(3):
    turtle.forward(150)
    turtle.left(120)

turtle.done()


import turtle

turtle.speed(10)

fondo = turtle.Screen()
fondo.bgcolor("gray")
turtle.pensize(2)

for i in range(4):
    turtle.forward(150)
    turtle.left(120)
    for i in range(1):
        turtle.forward(150)
        turtle.left(150)

turtle.done()

       
 

import turtle

turtle.speed(10)

fondo = turtle.Screen()
fondo.bgcolor("gray")
turtle.pensize(2)

for i in range(10):
    turtle.forward(150)
    turtle.left(120)
    for i in range(1):
        turtle.forward(150)
        turtle.left(80)

turtle.done()

import turtle

turtle.speed(10)

fondo = turtle.Screen()
fondo.bgcolor("gray")
turtle.pensize(2)

for i in range(12):
    turtle.forward(80)
    turtle.left(120)
    for i in range(1):
        turtle.forward(80)
        turtle.right(150)

turtle.done()

       
 


sábado, 14 de octubre de 2017

Barquito hecho con la librería turtle

from turtle import *

setup(600,600,0,0)
screensize(400,400)
pensize(3)

pencolor("black")

penup()
goto(200,50)
pendown()
fillcolor("orange")
begin_fill()
goto(100,-50)
goto(-100,-50)
goto(-200,50)
goto(200,50)
end_fill()

penup()
goto(0,50)
pendown()
goto(0,162.5)
goto(100,62.5)
goto(0,62.5)

fillcolor("brown")
begin_fill()
goto(0,175)
goto(-7,175)
goto(-7,50)
goto(0,50)
end_fill()

penup()
fillcolor("blue")
begin_fill()
goto(-300,-50)
pendown()
goto(-300,-150)
goto(300,-150)
goto(300,-50)
goto(-300,-50)
end_fill()

done()  

martes, 10 de octubre de 2017

Figuras con la librería Turtle

1. Paloma
from turtle import *

setup(360, 360, 0, 0)
screensize(330, 330)
title("Figura de Paloma")

pensize(2)
penup()
goto(-32,61)
pendown()
goto(-32,61)
goto(-6,43)
goto(35,12)
goto(58,-4)
goto(89,-13)
goto(91,-22)
goto(79,-28)
goto(103,-46)
goto(32,-20)
goto(16,-17)
goto(-12,-32)
goto(-14,-40)
goto(-3,-44)
goto(-47,-45)
goto(-21,-35)
goto(-15,-25)
goto(-20,-10)
goto(-33,-7)
goto(-63,15)
goto(-69,37)
goto(-63,75)
goto(-69,82)
goto(-82,81)
goto(-65,99)
goto(-48,99)
goto(-42,90)
goto(-32,61)
hideturtle()
done()


2. Canguro
from turtle import *

setup(500, 400, 0, 0)
screensize(400, 350)
title("Figura de Canguro")

pensize(2)

penup()
goto(-30,72)
pendown()
goto(-30,72)
goto(21,79)
goto(26,76)
goto(60,133)
goto(80,137)
goto(66,114)
goto(60,110)

penup()
goto(73,125)
pendown()
goto(73,125)
goto(102,89)
goto(94,78)
goto(62,99)
goto(63,36)
goto(55,2)
goto(57,-16)

goto(39,-3)
goto(24,6)
goto(-4,-17)
goto(-21,-68)
goto(22,-96)
goto(-32,-89)
goto(-39,-73)
goto(-41,-40)
goto(-59,-66)
goto(-237,-17)
goto(-67,-34)
goto(-67,-26)
goto(-30,72)

penup()
goto(13,-4)
pendown()
goto(13,-4)
goto(9,-45)
goto(63,-73)
goto(6,-66)
goto(-7,-49)
goto(-9,-31)
goto(-4,-17)
goto(13,-4)

penup()
goto(79,119)
pendown()
goto(79,119)
goto(84,121)
goto(97,144)
goto(80,137)
goto(73,125)
goto(81,117)

penup()
goto(58,9)
pendown()
goto(58,9)
goto(62,-11)
goto(56,-7)

hideturtle()
done()


3. Mariposa con Ecuaciones paramétricas
from turtle import *
import math

setup(500, 500, 0, 0)
screensize(400, 400)
title("Figura de Mariposa con Ecuaciones parametricas")
colormode(255)
pensize(2)

n=0
colores=["#201815","#584C4C","#3F6E80","#0F4851","#473A68","#201815","#584C4C","#3F6E80","#0F4851","#473A68"]

for t in range(0,3600):
    if(t%360==0):
        pencolor(colores[n])
        n=n+1
    t=t*((math.pi)/180)
    x = (math.sin(t) * ((math.exp(math.cos(t))) - (2 * math.cos(4*t)) - ((math.sin(t / 12)) ** 5)))*60
    y = (math.cos(t) * ((math.exp(math.cos(t))) - (2 * math.cos(4*t)) - ((math.sin(t / 12)) ** 5)))*60
    goto(x,y)

hideturtle()
done()