Código de Python - Vista 'grid' (demo)

Filtrado por el tag: scrip js
<<>>
Imágen de perfil
Val: 712
Bronce
Ha aumentado 1 puesto en Python (en relación al último mes)
Gráfica de Python

Vista 'grid' (demo)gráfica de visualizaciones


Python

Actualizado el 12 de Abril del 2025 por Antonio (77 códigos) (Publicado el 31 de Julio del 2023)
7.792 visualizaciones desde el 31 de Julio del 2023
El siguiente código muestra un grid en pantalla por el que se puede desplazar usando los botones de dirección:

Botón de dirección derecha: Desplazamiento hacia la derecha.
Botón de dirección izquierdo: Desplazamiento a la izquierda.
Botón de dirección superior: Desplazamiento hacia adelante.
Botón de dirección inferior: Desplazamiento hacia atrás.
Botones 'o', 'p', 'k' y 'l': Desplazamientos en diagonal.

grid

Requerimientos

Lenguaje: Python
Librerías y recursos: OpenGL, Pygame.

1.0

Actualizado el 19 de Noviembre del 2023 (Publicado el 31 de Julio del 2023)gráfica de visualizaciones de la versión: 1.0
1.149 visualizaciones desde el 31 de Julio del 2023

2.0

Actualizado el 30 de Junio del 2024 (Publicado el 30 de Diciembre del 2023)gráfica de visualizaciones de la versión: 2.0
3.658 visualizaciones desde el 30 de Diciembre del 2023

2.1

Actualizado el 12 de Abril del 2025 (Publicado el 28 de Agosto del 2024)gráfica de visualizaciones de la versión: 2.1
2.986 visualizaciones desde el 28 de Agosto del 2024
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

70ce251290efad096b9ee882684543c6b5faa23810050
dc4b22e5aa5e44697b5aaf17458faa6f7ba08c0d10050
vg
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#/usr/bin/env python
# -*- coding: utf-8 -*-
import pygame
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
 
grid_size = 140
grid_spacing = 1
 
vertices = (
    (1.0, 0.0, -1.0),
    (1.0, 0.5, -1.0),
    (-1.0, 0.5, -1.0),
    (-1.0, 0.0, -1.0),
    (1.0, 0.0, 1.0),
    (1.0, 1.0, 1.0),
    (-1.0, 0.0, 1.0),
    (-1.0, 1.0, 1.0)
)
 
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)
)
 
surfaces = (
    (0,1,2,3),
    (3,2,7,6),
    (6,7,5,4),
    (4,5,1,0),
    (1,5,7,2),
    (4,0,3,6)
    )
 
def draw_grid():
    grid_list = glGenLists(1)
    glNewList(grid_list, GL_COMPILE)
    glLineWidth(1.3)
    glBegin(GL_LINES)
    glColor3f(1.0,1.0,1.0)
 
    for x in range(-grid_size, grid_size + 1, grid_spacing):
        glVertex3f(x, 0, -grid_size)
        glVertex3f(x, 0, grid_size)
 
    for z in range(-grid_size, grid_size + 1, grid_spacing):
        glVertex3f(-grid_size, 0, z)
        glVertex3f(grid_size, 0, z)
 
    glEnd()
    glEndList()
    return grid_list
 
def show_controls():
    print("\n--------------------- Controls ---------------------")
 
    print("\nKeyboard Controls:")
    print("  - Up Arrow: Move forward in the scene")
    print("  - Down Arrow: Move backward in the scene")
    print("  - Left Arrow: Move left in the scene")
    print("  - Right Arrow: Move right in the scene")
 
    print("\nRotation Controls:")
    print("  - 'T' Key: Rotate the scene clockwise")
    print("  - 'R' Key: Rotate the scene counterclockwise")
    print("  - 'Q' Key: Tilt the scene upwards")
    print("  - 'W' Key: Tilt the scene downwards")
 
    print("\nSpeed Controls:")
    print("  - 'Z' Key: Increase camera movement speed")
    print("  - 'X' Key: Decrease camera movement speed")
    print("  - 'C' Key: Increase figure movement speed")
    print("  - 'V' Key: Decrease figure movement speed")
 
    print("\nMiscellaneous:")
    print("  - 'H' Key: Toggle visibility of on-screen data")
    print("  - 'P' Key: Pause the figure movement")
    print("  - 'L' Key: Restore the view to the original position")
    print("  - 'ESC' Key: Close the application (close window)")
 
    print("\n----------------------------------------------------")
 
 
def Cube():
    cube_list = glGenLists(1)
    glNewList(cube_list, GL_COMPILE)
    glLineWidth(3.0)
    glBegin(GL_LINES)
    glColor3f(1.0, 0.0, 0.0)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(vertices[vertex])
    glEnd()
 
    glBegin(GL_QUADS)
    glColor3f(0.0,0.0,1.0)
    for surface in surfaces:
        for vertex in surface:
            glVertex3fv(vertices[vertex])
    glEnd()
 
    glEndList()
    return cube_list
 
def drawText(f, x, y, text, c, bgc):
    textSurface = f.render(text, True, c, bgc)
    textData = pygame.image.tostring(textSurface, "RGBA", True)
    glWindowPos2d(x, y)
    glDrawPixels(textSurface.get_width(), textSurface.get_height(), GL_RGBA, GL_UNSIGNED_BYTE, textData)
 
def main():
    pygame.init()
    display = (800, 600)#(1600, 880)
    pygame.display.set_mode(display, DOUBLEBUF | OPENGL)
    gluPerspective(45, (display[0] / display[1]), 0.1, 90.0) #90
    glTranslatef(0.0, 0.0, -10)
    glEnable(GL_DEPTH_TEST)
    font = pygame.font.SysFont('arial', 15)
    glRotatef(15, 1, 0, 0)
 
    cube_list = Cube()
    grid_list = draw_grid()
    hide_data = False
 
    #glEnable(GL_BLEND)
    #glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
 
    show_controls()
 
    x = 0
    z = 0
 
    x_c = 0#
    z_c = 0#
 
    angle = 0
    speed = 0.1#0.090
    speed_c = 0.1#0.090#
    running = True
    direction = 'front'
 
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_DOWN and direction != "back":
                    direction = "back"
                    angle = 180
                elif event.key == pygame.K_UP and direction != "front":
                    direction = "front"
                    angle = 0
                elif event.key == pygame.K_RIGHT and direction != "right":
                    direction = "right"
                    angle = -90
                elif event.key == pygame.K_LEFT and direction != "left":
                    direction = "left"
                    angle = 90
                elif event.key == pygame.K_d:
                    speed = 0.1
                    speed_c = 0.1
                elif event.key == pygame.K_p:
                    speed_c = 0.000
                elif event.key == pygame.K_h:
                    if hide_data == True:
                        hide_data = False
                    else:
                        hide_data = True
                elif event.key == pygame.K_ESCAPE:
                    running = False
                elif event.key == pygame.K_l:
                    # Restaurar la vista original
                    direction = 'front'
                    x = 0
                    z = 0
                    x_c = 0
                    z_c = 0
                    angle = 0
                    speed = 0.1
                    speed_c = 0.1
 
                    # Restaurar las rotaciones acumuladas
                    glLoadIdentity()  # Resetea las transformaciones
                    gluPerspective(45, (display[0] / display[1]), 0.1, 90.0)  # Reestablece la perspectiva
                    glTranslatef(0.0, 0.0, -10)  # Reestablece la cámara alejada
                    glRotatef(15, 1, 0, 0)
 
 
 
 
        key = pygame.key.get_pressed()
 
        if key[pygame.K_UP]: #and z + speed <= (grid_size - 1):
            z += speed
            z_c -= speed_c
            z_c += speed
        if key[pygame.K_DOWN]: #and z - speed >= (-grid_size + 1):
            z -= speed
            z_c += speed_c
            z_c -= speed
        if key[pygame.K_RIGHT]: #and x - speed >= (-grid_size + 1):
            x -= speed
            x_c += speed_c
            x_c -= speed
        if key[pygame.K_LEFT]: #and x + speed <= (grid_size - 1):
            x += speed
            x_c -= speed_c
            x_c += speed
 
        if key[pygame.K_t]:
            glRotatef(1, 0, -0.1, 0)
        elif key[pygame.K_r]:
            glRotatef(1, 0, 0.1, 0)
        elif key[pygame.K_q]:
            glRotatef(1, -0.1, 0, 0)
        elif key[pygame.K_w]:
            glRotatef(1, 0.1, 0, 0)
 
        if key[pygame.K_z]:
            speed += 0.001
        elif key[pygame.K_x]:
            speed -= 0.001
        elif key[pygame.K_c]:
            speed_c += 0.001
        elif key[pygame.K_v]:
            speed_c -= 0.001
 
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
 
        # Grid
        glPushMatrix()
        glTranslatef(x, 0.00, z)
        glCallList(grid_list)
        glPopMatrix()
 
        # Figura
        glPushMatrix()
        glTranslatef(x_c, 0.0, z_c)
        glRotatef(angle, 0, 1, 0)
        glCallList(cube_list)
        glPopMatrix()
 
        spd = round(speed, 3)
        spdc = round(speed_c, 3)
 
        if hide_data == False:
            drawText(font, 20, 570, f'DIRECTION: {direction}',(0, 255, 0, 255),(0,0,0))
            drawText(font, 20, 550, f'CAMERA SPEED: {spd}',(0, 255, 0, 255),(0,0,0))
            drawText(font, 20, 530, f'FIGURE SPEED: {spdc}',(0, 255, 0, 255),(0,0,0))
        #glFlush()
        pygame.display.flip()
        pygame.time.wait(10)
 
    glDeleteLists(grid_list, 1)
    glDeleteLists(cube_list, 1)
    pygame.quit()
 
main()



Comentarios sobre la versión: 2.1 (0)


No hay comentarios
 

Comentar la versión: 2.1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s7403