martes, 7 de noviembre de 2017

3D En Python

En esta publicacion lo que se les pretende realizar es una pequeña introduccion a python pero ahora en 3D sobre diferentes figuras

1.- CUBO

import pygame
from pygame.locals import *

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

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

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


def piramide():
    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)
        piramide()
        pygame.display.flip()
        pygame.time.wait(10)

main()


---------------------------------------------------------------------------------------------
2.- PIRAMIDE 

import pygame
from pygame.locals import *

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

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

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


def piramide():
    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)
        piramide()
        pygame.display.flip()
        pygame.time.wait(10)

main()


Estas Figuras Fueron realizadas por mi compañero Aquino 
y este es su blog por si lo quieren ir a ver :

http://eduardommm.blogspot.mx/

--------------------------------------------------------------------------------------------
3.- Cubo De 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()



Este programa fue realizado por el equipo de Gilberto,Edgar y Luis y aqui esta el link :

mendezitmg.blogspot.mx


---------------------------------------------------------------------------------------------
4.- Gráfica De Barras
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='red')
plt.show()

Este programa fue realizado por Ivan Guzman:

iscivanguz.blogspot.mx
























miércoles, 11 de octubre de 2017

Turtle en Python




¿Qué es Turtle en python?
Es un objeto que se importa de la libreria turtle en python.


--------------------------------------------------------------------------------------------------------------------------
En esta practica  permite definir el tamañoy la posicion inicial .
setup(ancho, alto, posicionX, posicionY)


from turtle import *

setup(640, 480, 0, 0)


--------------------------------------------------------------------------------------------------------------------------
Practica sele implementa un titulo en la ventana 
from turtle import *

setup(450, 150, 0, 0)
title("Ejemplo de ventana")



















--------------------------------------------------------------------------------------------------------------------------

En esta practica se puede modificar el tamaño de la ventana de dibujo se puede modificar a lo largo de un programa y si perde lo que ya tienes realizado anteri
from turtle import *

setup(250, 100, 0, 0)
title("Ejemplo de ventana")
hideturtle()
dot(10, 0, 0, 0)
setup(450, 150, 0, 0)




-------------------------------------------------------------------------------------------------------------------------
En esta practica se activa la barras de desplazamiento 



from turtle import *

setup(150, 150, 0, 0)
screensize(300, 300)





-------------------------------------------------------------------------------------------------------------------------
En esta solo se activa la barra de desplazamiento vertical 



from turtle import *

setup(450, 150, 0, 0)
screensize(400, 300)



-------------------------------------------------------------------------------------------------------------------------


En esta practica lo que hace es que el tamaño del área de dibujo se puede modificar a lo largo de un programa, sin perder el dibujo realizado.

from turtle import *

setup(250, 100, 0, 0)
screensize(100, 100)
hideturtle()
dot(10, 0, 0, 0)
screensize(200, 100)



-------------------------------------------------------------------------------------------------------------------------
En esta practica se ve que con goto se puede posicionar el dibujo final 

from turtle import *
shape("turtle")
setup(450, 150, 0, 0)
screensize(300, 150)

goto(100, 0)




-------------------------------------------------------------------------------------------------------------------------

Con esta  función hideturtle() oculta el cursor (la tortuga).
from turtle import *

setup(450, 150, 0, 0)
screensize(300, 150)

goto(100, 0)
hideturtle()



-------------------------------------------------------------------------------------------------------------------------

Si el primer goto() desplaza a un punto distinto, se dibuja la línea entre el punto inicial (0, 0) y el indicado
from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)

goto(100, 50)



-------------------------------------------------------------------------------------------------------------------------
Si se escriben varias instrucciones goto(), se van dibujando los segmentos uno a continuación del otro
from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)

goto(100, 50)
goto(100, -50)
goto(50, -50)



-------------------------------------------------------------------------------------------------------------------------
Las funciones pendown() y penup() son equivalentes a bajar y levantar el lápiz del papel. Una vez levantado el lápiz del papel, al desplazar el lápiz ya no se dibujan segmentos. Al volver a bajar el lápiz, al desplazar el lápiz vuelven a dibujarse los fragmentos.

from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)

goto(100, 50)
penup()
goto(100, -50)
pendown()
goto(50, -50)




-------------------------------------------------------------------------------------------------------------------------

La función pensize(grosor) permite modificar el grosor del trazo.


from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)

goto(100, 50)
pensize(4)
goto(100, -50)
pensize(8)
goto(50, -50)




-------------------------------------------------------------------------------------------------------------------------

En esta practica se le agrega color a las lineas hay varias formas por cordenadas por RGB o Por el nombre del como con Pencolor.
from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)

pencolor("red")
goto(100, 50)
pencolor("green")
goto(100, -50)
pencolor("blue")
goto(50, -50)




-------------------------------------------------------------------------------------------------------------------------

La función dot(grosor, color) permite dibujar un punto del grosor y color indicado en el punto en el que se encuentra el cursor. El grosor se indica en píxeles y el color se expresa como en la función pencolor() vista en el apartado anterior (entre paréntesis, como tupla, o sin paréntesis).


from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
colormode(255)

goto(100, 50)
dot(10, 255, 0, 0)
goto(100, -50)
dot(10, 0, 255, 0)
goto(50, -50)
dot(10, 0, 0, 255)
goto(0,0)




-------------------------------------------------------------------------------------------------------------------------
Si queremos dibujar únicamente puntos, basta con levantar el lápiz (no es necesario bajarlo para dibujar puntos).

from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
colormode(255)

penup()
goto(100, 50)
dot(10, 255, 0, 0)
goto(100, -50)
dot(10, 0, 255, 0)
goto(50, -50)
dot(10, 0, 0, 255)
goto(0,0)




-------------------------------------------------------------------------------------------------------------------------
La función begin_fill() indica a Python que las figuras que se dibujen a partir de ese momento se deben rellenar. La función end_fill() indica a Python que las figuras deben dejar de rellenarse.

from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(100, 0)
goto(100, 50)
goto(0, 50)
goto(0, 0)
end_fill()



-------------------------------------------------------------------------------------------------------------------------
Si no se establece un color de relleno distinto, el color de relleno predeterminado es el negro.
from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pencolor("red")
pensize(5)
begin_fill()
goto(100, 0)
goto(100, 50)
goto(0, 50)
goto(0, 0)
end_fill()

-------------------------------------------------------------------------------------------------------------------------


Aunque realmente no es necesario dibujar la figura completa ya que Python rellena la figura aunque no se cierre la figura (es como si Python uniera el último punto de la figura con el primero).


from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(100, 0)
goto(100, 50)
goto(0, 50)
end_fill()




-------------------------------------------------------------------------------------------------------------------------
Si las líneas de la figura se cruzan, Python rellena cada una de las partes cerradas.



from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(50, 50)
goto(100, -50)
goto(150, 0)
goto(0, 0)
end_fill()














-------------------------------------------------------------------------------------------------------------------------
Si las líneas de la figura se cruzan, Python también rellena la figura aunque no se cierre la figura (es como si Python uniera el último punto de la figura con el primero).


from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(0, 75)
goto(100, 0)
goto(100, 75)
end_fill()

-------------------------------------------------------------------------------------------------------------------------
Cuando se levanta el lápiz, Python incluye el trayecto en la figura a rellenar ...


from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(75, 0)
goto(75, 75)
penup()
goto(-100, 75)
pendown()
goto(-100,0)
goto(-25, 0)
end_fill()




-------------------------------------------------------------------------------------------------------------------------



from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(75, 0)
goto(75, 75)
end_fill()
penup()
goto(-100, 75)
pendown()
begin_fill()
goto(-100,0)
goto(-25, 0)
end_fill()


-------------------------------------------------------------------------------------------------------------------------

from turtle import *

setup(450, 200, 0, 0)
screensize(300, 150)
title("www.mclibre.org")
hideturtle()

pensize(5)
fillcolor("red")
begin_fill()
goto(75, 0)
goto(75, 75)
goto(0,0)
penup()
goto(-100, 75)
pendown()
goto(-100,0)
goto(-25, 0)
goto(-100, 75)
end_fill()

-------------------------------------------------------------------------------------------------------------------------
from turtle import *


shape("turtle")
title("Ejemplo de ventana")
hideturtle()
setup(450, 150, 0, 0)
screensize(300, 150)
colormode("yellow")

pensize(1)
fillcolor("black")
penup()
goto(-130,-50)


pendown()
begin_fill()
goto(-150,-40)
goto(-130,-30)
goto(-130,-70)
goto(-130,-50)
end_fill()


pensize(2)
fillcolor("Red")
penup()
goto(-80,-70)

pendown()
begin_fill()
goto(-180,-70)
goto(-160,-100)
goto(-110,-100)
goto(-80,-70)
end_fill()


done()







--------------------------------------------------------------------------------------------------------------------------
En estas practicas se utiliza los For anidados :

Estrella :

import turtle

turtle.speed(10)

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

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

turtle.done()




--------------------------------------------------------------------------------------------------------------------------
Cuadrado 

import turtle

turtle.speed(10)

fondo=turtle.Screen()
fondo.bgcolor("#0000FF")
turtle.pencolor("black")
for i in range(28):
 turtle.forward(100)
 turtle.right(90)
 for j in range(1):
  turtle.forward(100)
  turtle.right(80)


turtle.exitonclick()





--------------------------------------------------------------------------------------------------------------------------



import turtle

turtle.speed(10)

fondo=turtle.Screen()
fondo.bgcolor("green")
turtle.pencolor("black")

for i in range(28):
 turtle.forward(100)
 turtle.right(120)
 for j in range(1):
  turtle.forward(100)
  turtle.right(100)


turtle.exitonclick()



















Enlace :
http://www.mclibre.org/consultar/python/lecciones/python-turtle-1.html

Unidad 4: Operación y Mantenibilidad

Unidad 4: Operación y Mantenibilidad 4.1 Bitácoras de Trabajo del DBMS Una bitácora es una herramienta (archivos o registros) que pe...