全代码展示,讲解看下篇博客
exe免费纯享版地址:https://download.csdn.net/download/jianmuhuayi/26050493
import pygame
from pygame.locals import *
from sys import exit
from math import cos,sin,tan,radians
pygame.init()
p={}
width=600
color=(0,0,0)
fov=70
focus=(width/2)/tan(radians(fov/2))
screen = pygame.display.set_mode((width, width), 0,0)
screen.fill((255,255,255))
pygame.display.set_caption('3D project')
pygame.mouse.set_visible(False)
pygame.event.set_grab(True)
p['pa']=[-500,-500,800]
p['pb']=[-500,500,800]
p['pc']=[500,500,800]
p['pd']=[500,-500,800]
p['pe']=[-500,-500,1800]
p['pf']=[-500,500,1800]
p['pg']=[500,500,1800]
p['ph']=[500,-500,1800]
def rotatex(angle_x):
for coordinate in p.values():
coordinate_z_new=coordinate[2]*cos(angle_x)+coordinate[1]*sin(angle_x)
coordinate_y_new=coordinate[1]*cos(angle_x)-coordinate[2]*sin(angle_x)
coordinate[1]=coordinate_y_new
coordinate[2]=coordinate_z_new
def rotatey(angle_x):
for coordinate in p.values():
coordinate_x_new=coordinate[0]*cos(angle_x)-coordinate[2]*sin(angle_x)
coordinate_z_new=coordinate[2]*cos(angle_x)+coordinate[0]*sin(angle_x)
coordinate[0]=coordinate_x_new
coordinate[2]=coordinate_z_new
def bjo(p_a,p_b):
global focus
global color
if focus<=p_a[2]:
if focus<=p_b[2]:
pygame.draw.aaline(screen,color,(p_a[0]/p_a[2]*focus+300, 300-p_a[1]/p_a[2]*focus), (p_b[0]/p_b[2]*focus+300 ,300-p_b[1]/p_b[2]*focus))
else:
pygame.draw.aaline(screen,color,((focus-p_a[2])*(p_b[0]-p_a[0])/(p_b[2]-p_a[2])+p_a[0]+300,300-((focus-p_a[2])*(p_b[1]-p_a[1])/(p_b[2]-p_a[2])+p_a[1])), (p_a[0]/p_a[2]*focus+300, 300-p_a[1]/p_a[2]*focus))
else:
if focus<=p_b[2]:
pygame.draw.aaline(screen,color,((focus-p_a[2])*(p_b[0]-p_a[0])/(p_b[2]-p_a[2])+p_a[0]+300,300-((focus-p_a[2])*(p_b[1]-p_a[1])/(p_b[2]-p_a[2])+p_a[1])), (p_b[0]/p_b[2]*focus+300, 300-p_b[1]/p_b[2]*focus))
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
exit()
screen.fill((255,255,255))
pressed_keys = pygame.key.get_pressed()
if True:
mouse=pygame.mouse.get_rel()
y=radians(mouse[0]/width*180)
x=-radians(mouse[1]/width*180)
else:
x=0
y=0
rotatey(y)
rotatex(x)
if pressed_keys[K_a]:
for coordinate in p.values():
coordinate[0]+=1
elif pressed_keys[K_d]:
for coordinate in p.values():
coordinate[0]-=1
if pressed_keys[K_w]:
for coordinate in p.values():
coordinate[2]-=1
elif pressed_keys[K_s]:
for coordinate in p.values():
coordinate[2]+=1
bjo(p['pa'],p['pb'])
bjo(p['pb'],p['pc'])
bjo(p['pc'],p['pd'])
bjo(p['pd'],p['pa'])
bjo(p['pe'],p['pf'])
bjo(p['pf'],p['pg'])
bjo(p['pg'],p['ph'])
bjo(p['ph'],p['pe'])
bjo(p['pa'],p['pe'])
bjo(p['pb'],p['pf'])
bjo(p['pc'],p['pg'])
bjo(p['pd'],p['ph'])
pygame.display.update()
|