domingo, 12 de noviembre de 2017

EJERCICIOS

Vértices Cubo Python


CUBO 3D 
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()

Triangulo 3D (Pirámide)
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 = (
    (4, 0),
    (4, 1),
    (4, 2),
    (4, 3),
    (0, 1),
    (0, 3),
    (2, 1),
    (2, 3)

)


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()

CUBO 3D 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("Simulation of a rotating 3D Cube (http://codeNtronix.com)")

        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,69,0), (255,140,0), (255,165,0), (255,215,0), (255,255,0), (255, 200, 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()
GRÁFICO 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]
ypos = [2,3,4,5,10,6,2,1,7,2]
num_elements = len(xpos)
zpos = [0,0,0,0,0,0,0,0,0,0]
dx = np.ones(10)
dy = np.ones(10)
dz = [1,2,3,4,5,6,7,8,9,10]

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

JUEGO EN PYTHON
*Código del juego*


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


# Iluminación personalizada de la animaciónclass Luz(object):
    encendida = True    colores = [(5, 0, 1, 1), (12., 20, 0.5, 8),
               (8.5,35,5,14), (2,3,1.,4)]
    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 Esferaclass 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 principalclass 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()

PINO 3D PYTHON
from visual import *

floor = box(pos=vector(0,-0.1,0),size=vector(2,24,24), axis=vector(0,1,0), color= color.orange, material = materials.bricks)
tronco = cylinder(pos= (0,0,0), axis=(0,10,0), radius = 0.5,color=color.orange, material=materials.wood)
cono1= cone(pos= (0,10,0), radius=1, axis=(0,5,0), color= color.green, material = materials.rough)
#Capa1

cono2= cone(pos= (0,9,0), radius=1, axis=(3,3,0), color= color.green)
cono3= cone(pos= (0,9,0), radius=1, axis=(-3,3,0), color= color.green)
cono4= cone(pos= (0,9,0), radius=1, axis=(0,3,3), color= color.green)
cono5= cone(pos= (0,9,0), radius=1, axis=(0,3,-3), color= color.green)
#Capa2

cono6= cone(pos= (0,8,0), radius=1, axis=(3,1,0), color= color.green)
cono7= cone(pos= (0,8,0), radius=1, axis=(-3,1,0), color= color.green)
cono8= cone(pos= (0,8,0), radius=1, axis=(0,1,3), color= color.green)
cono9= cone(pos= (0,8,0), radius=1, axis=(0,1,-3), color= color.green)
#Capa3

cono10= cone(pos= (0,7,0), radius=1, axis=(3,-1,0), color= color.green)
cono11= cone(pos= (0,7,0), radius=1, axis=(-3,-1,0), color= color.green)
cono12= cone(pos= (0,7,0), radius=1, axis=(0,-1,3), color= color.green)
cono13= cone(pos= (0,7,0), radius=1, axis=(0,-1,-3), color= color.green)





martes, 31 de octubre de 2017

Pyglet

  • Pyglet
  •  Pyglet es la alternativa a Pygame+PyOpenGL permitiendo aceleración gráfica y trabajar en 2d/3d, todo ello en una sola librería, y sin tener que recurrir a la engorrosa dificultad de PyOpenGL. Eso sí, sacrificando algunas utilidades avanzadas de pyopengl, y siendo un poco más dificil de usar que Pygame. Pyglet es una librería con un desarollo actual más rápido que pygame, que cada día gana más adeptos. En realidad Pyglet utiliza OpenGL en gran parte de sus funciones, pero facilitando su uso.

video
https://www.youtube.com/watch?v=Y9H6iYqnlqE




CODIGO:

import pyglet
from pyglet.gl import *
window = pyglet.window.Window()
@window.eventdef on_draw():
    glClear(GL_COLOR_BUFFER_BIT)
    glMatrixMode(GL_MODELVIEW)
    glBegin(GL_TRIANGLES)
    glVertex2i(300,300)
    glColor3f(0,1,0)
    glVertex2i(400,200)
    glColor3f(1,0,0)
    glVertex2i(200,200)
    glColor3f(0,0,1)
    glEnd()
pyglet.app.run();


sábado, 21 de octubre de 2017

Turtle 19 Octubre

Programa 1

from turtle import*
import tkSimpleDialog

speed(10)

shape("turtle")
vueltas=30
a=tkSimpleDialog.askstring("Hola", "Color de fondo")
b=tkSimpleDialog.askstring("Hola","Dame color de relleno")
pluma=tkSimpleDialog.askinteger("Numero de pixeles"," grosor Pluma")

bgcolor(a)
pensize(pluma)
fillcolor(b)

begin_fill()
cont=0for i in range(vueltas):
    if cont > 14:
        clear(); cont=0; i=1; vueltas=1;

    begin_fill()
    rt(90)
    fd(200)
    lt(120)
    fd(200)
    lt(120)
    fd(200)
    end_fill()

    cont= cont+1    print vueltas

exitonclick()


Programa 2
from turtle import*
import tkSimpleDialog

speed(10)
shape("turtle")

c=tkSimpleDialog.askstring("Hola", "Color de fondo")
a=tkSimpleDialog.askstring("Hola","Dame color de relleno")
vueltas=tkSimpleDialog.askinteger("Numero de figuras","figuras")
pluma=tkSimpleDialog.askinteger("Numero de pixeles"," grosor Pluma")

bgcolor(c)
pensize(pluma)
fillcolor(a)

cont=0a=90b=200c=120
for i in range(vueltas):
    begin_fill()
    rt(90)
    fd(200)
    lt(120)
    fd(200)
    lt(120)
    fd(200)
    end_fill()
    cont= cont+1

exitonclick()


Programa 3

from turtle import*
import tkSimpleDialog

speed(10)
shape("turtle")

c=tkSimpleDialog.askstring("Hola", "Color de fondo")
a=tkSimpleDialog.askstring("Hola","Dame color de relleno")
vueltas=tkSimpleDialog.askinteger("Numero de figuras","figuras")
pluma=tkSimpleDialog.askinteger("Numero de pixeles"," grosor Pluma")

bgcolor(c)
pensize(pluma)
fillcolor(a)

cont=0a=90b=200c=120
for i in range(vueltas):
    if cont >8:
        clear(); cont=0; i=1; vueltas=1;
    begin_fill()
    rt(90)
    fd(200)
    lt(120)
    fd(200)
    lt(120)
    fd(200)
    end_fill()
    cont= cont+1
exitonclick()




Figuras con relleno TURTLE

Cuadrado

import turtle
import tkSimpleDialog
t = turtle.Turtle()
c1=tkSimpleDialog.askstring(" Color","Contorno")
c2=tkSimpleDialog.askstring("Relleno","Color de figura")

pen_color = c1
fill_color = c2
t.color(c1,c2)


t.begin_fill()
for _ in range(4):
    t.fd(100)
    t.left(90)

t.end_fill()

turtle.exitonclick()

Triangulo

import turtle
import tkSimpleDialog
t = turtle.Turtle()
c1=tkSimpleDialog.askstring(" Color","Contorno")
c2=tkSimpleDialog.askstring("Relleno","Color de figura")
pen_color = c1
fill_color = c2
t.color(c1,c2)


t.begin_fill()
for _ in range(3):
    t.fd(100)
    t.left(120)

t.end_fill()

turtle.exitonclick()

Octágono

import turtle
import tkSimpleDialog
t = turtle.Turtle()
c1=tkSimpleDialog.askstring(" Color","Contorno")
c2=tkSimpleDialog.askstring("Relleno","Color de figura")

pen_color = c1
fill_color = c2
t.color(c1,c2)
t.begin_fill()
for _ in range(8):
    t.fd(100)
    t.left(45)
t.end_fill()
turtle.exitonclick()




martes, 10 de octubre de 2017

TURTLE

BARCO


from turtle import *

setup(700,500, 0, 0)
screensize(200, 150)

penup()
goto(0,0 )
goto(75,100)

pendown()
pensize(3)
fillcolor("white")
begin_fill()
goto(75,100)
goto(150,225)
goto(225,100)
end_fill()

penup()
goto(225,100)
goto(25,100)

pendown()

fillcolor("Dark Turquoise")
begin_fill()
goto(25,100)
goto(275,100)
goto(200,25)
goto(100,25)
goto(25,100)
end_fill()

penup()
goto(25,100)
goto(50,75)

pendown()
goto(50,75)
goto(250,75)

penup()
goto(250,75)
goto(150,225)

pendown()
goto(150,225)
goto(150,100)

done()
PINO


from turtle import *

setup (
450,200,0,0)
screensize (
300,150)
title(
"ventana")
hideturtle()
pensize(
5)
fillcolor(
"green")
begin_fill()
goto(
100,0)
goto(
50,100)
goto (
0,0)
end_fill()
fillcolor(
"brown")
begin_fill()
goto(
40,0)
goto(
40,-50)
goto(
60,-50)
goto (
60,0)
end_fill()
done()

FIGURA

from turtle import *

setup(700,500, 0, 0)
screensize(200, 150)

penup()
goto(0,0 )
goto(200,120)

pendown()
pensize(3)
fillcolor("deeppink")
begin_fill()
goto(200,120)
goto(200,80)
goto(240,120)
goto(280,80)
goto(280,120)
goto(320,120)
goto(280,160)
goto(320,200)
goto(280,200)
goto(280,240)
goto(240,200)
goto(200,240)
goto(200,200)
goto(160,200)
goto(200,160)
goto(160,120)
goto(200,120)
end_fill()

penup()
goto(160,120)
goto(220,140)

pendown()

fillcolor("yellow")
begin_fill()
goto(220,140)
goto(220,180)
goto(260,180)
goto(260,140)
goto(220,140)
end_fill()

penup()
goto(240,120)
goto(240,120)

pendown()
goto(240,120)
goto(240,0)

penup()
goto(240,0)
goto(240,0)

pendown()
fillcolor("green")
begin_fill()
goto(240,0)
goto(280,40)
goto(320,40)
goto(280,0)
goto(240,0)
goto(200,0)
goto(160,40)
goto(200,40)
goto(240,0)
end_fill()

done()
Ejemplos Turtle