jueves, 30 de noviembre de 2017

Figura en java

Código del botón:

 int[] x={       420,
                           420,
                           380,
                           300,
                           260,
                           260,
                           220,
                           180,
                           140,
                           140,
                           150,
                           200,
                           200,
                           160,
                           90,
                           100,
                           120,
                           200,
                           200,
                           160,
                           160,
                           180,
                           220,
                           220,
                           280,
                           280,
                           260,
                           260,
                           400,
                           360,
                           320,
                           280};
       
        int[] y={      180,
                           60,
                           100,
                           100,
                           60,
                           140,
                           100,
                           100,
                           140,
                           80,
                           80,
                           40,
                           20,
                           20,
                           80,
                           160,
                           270,
                           270,
                           230,
                           230,
                           210,
                           190,
                           190,
                           270,
                           270,
                           230,
                           230,
                           180,
                           200,
                           220,
                           220,
                           180};
        hila.hacergato(jPanel1.getGraphics(), x, y, 32);


Codigo del metodo:
public static void hacergato(Graphics g,int[] x, int[] y, int n){
        g.drawPolygon(x, y, n);

    }

miércoles, 8 de noviembre de 2017

Gráfica de barras 3D

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


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 = 1dy =1dz = [20,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()

martes, 7 de noviembre de 2017

Cubo en python con pygame y openGL

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

Cubo en python 3D de otra forma

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, 100), (100, 0, 0), (0, 25, 0), (0, 0, 255), (0, 255, 155), (255,5, 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()

Triangulo 3D en python

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 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, 23 de octubre de 2017

Mini-paint usando turtle

# -*- coding: utf-8 -*-

import turtle
import Tkinter
import tkColorChooser
import tkSimpleDialog


pantalla = Tkinter.Tk()
pantalla.title("Mini paint")
pantalla.resizable(False ,False)
#Se crea la pantalla que contendra la tortuga y el menu



canvas1 = Tkinter.Canvas(pantalla, width=750, height=750)
canvas1.pack(side="left", fill="both", expand=True)
canvas2 = Tkinter.Canvas(pantalla, width=750, height=750)
canvas2.pack(side="right", fill="both", expand=True)
#Se cean los 2 canvas que estaran en la pantalla

lapiz=turtle.RawTurtle(canvas1)
 
#Secrea una rawturtle y se le dice que ponga su area de dibujo en el canvas 1

lapiz.ondrag(lapiz.goto,btn=1)
 
#Se le ordena a la tortuga que se dirija al lugar al que el usuario 
#la arrastre (ondrag) con el boton 1 (click izquierdo)#La funcion ondrag al ejecutarse regresa 2 valores , la posicion de x y y en el momento
# en el que el usuario hace click sobre la tortuga , estas coordenadas son resividas por el goto


boton101= Tkinter.Button(canvas2,text="Color del lapiz",command=lambda:lapiz.pencolor(color2()))
boton101.pack(fill="x")
boton11= Tkinter.Button(canvas2,text="Grosor del lapiz",command=lambda:tamano())
boton11.pack(fill="x")
boton12= Tkinter.Button(canvas2,text="Color del relleno",command=lambda:lapiz.fillcolor(color2()))
boton12.pack(fill="x")
boton12= Tkinter.Button(canvas2,text="Cuadrado",command=lambda:cuadradi())
boton12.pack(fill="x")
boton12= Tkinter.Button(canvas2,text="Triangulo",command=lambda:triangulo())
boton12.pack(fill="x")
boton12= Tkinter.Button(canvas2,text="Circulo",command=lambda:circulo())
boton12.pack(fill="x")
boton12= Tkinter.Button(canvas2,text="Linea recta",command=lambda:linearecta())
boton12.pack(fill="x")
boton13= Tkinter.Button(canvas2,text="Limpiar",command=lambda:limpiar())
boton13.pack(fill="x")
boton14= Tkinter.Button(canvas2,text="subir y bajar lapiz",command=lambda:sube(lapiz.isdown()))
boton14.pack(fill="x")
boton14= Tkinter.Button(canvas2,text="Borrador",command=lambda:(lapiz.pencolor("White"),lapiz.pensize(10)))
boton14.pack(fill="x")
boton14= Tkinter.Button(canvas2,text="Lapiz",command=lambda:(lapiz.pencolor("black"),lapiz.pensize(1)))
boton14.pack(fill="x")
#Menu


def color2():
    a=tkColorChooser.askcolor()
    return (a[1])
    #Funcion que asigna un color al lapiz o el relleno con ayuda de la libreria tkColorChooser , 
    #la funcion tkColorChooser.askcolor() regresa el color seleccionado en forma de RGB y de hexadecimal 
    #de la forma  (RGB, hexadecimal)    #Al escribir a[1] estamos pidiendo la notacion hexadecimal del color

def tamano():
    a=tkSimpleDialog.askinteger("Hola","Dame el grosor del lapiz")
    lapiz.pensize(a)
    #Funcion que pide el tamaño del lapiz por meedio de un tkSimpleDialog.askinteger y lo asigna al lapiz


def limpiar():
    lapiz.clear()
    #Funcion que limpia el area de dibujo

def sube(a):
    if (a==False):
        lapiz.pendown()
    elif (a==True):
        lapiz.penup()
        #Funcion que se usa para subir y bajar el lapiz , para poder dibujar de forma mas realista


def cuadradi():
    lapiz.begin_fill()
    a=tkSimpleDialog.askinteger("Hola", "Dime el tamano del cuadrado")
    for x in range(4):
        lapiz.forward(a)
        lapiz.right(90)
    lapiz.end_fill()

def triangulo():
    lapiz.begin_fill()
    a=tkSimpleDialog.askinteger("Hola", "Dime el tamano del Triangulo")
    for x in range(3):
        lapiz.forward(a)
        lapiz.left(120)
    lapiz.end_fill()

def circulo():
    lapiz.begin_fill()
    a=tkSimpleDialog.askinteger("Hola", "Dime el tamano del circulo")
    lapiz.circle(a)
    lapiz.end_fill()
#Funciones que crean figuras predeterminadas

def linearecta():
    lapiz.begin_fill()
    a=tkSimpleDialog.askinteger("Hola", "Dime el tamano de la linea")
    b=tkSimpleDialog.askinteger("Hola", "Dime el angulo de la linea")
    c=tkSimpleDialog.askinteger("Hola", "Dime el numero de lineas")
    for i in range(c):
     lapiz.left(b)
     lapiz.forward(a)
    lapiz.end_fill()
#Funcion que le permite al usuario crear lineas rectas y
# seleccionar el angulo de las mismas , asi como el numero de veces que dicha 
#linea sera dibujada ,para que asi se pueda#crear cualquier poligino regular

pantalla.mainloop()