Pygame直线绘制

文章目录

pygame.draw中有4个绘制直线的函数,列表如下

一条线段 多条线段
正常 line lines
抗锯齿 aaline aalines

一条和多条线段的输入参数如下

  • line(surface, color, start_pos, end_pos, width=1)
  • lines(surface, color, closed, points, width=1)

lines

下面演示一下多条线段的用法,实现下面这种动感的随机直线生成窗口

代码如下

python 复制代码
import time
import numpy as np
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 320))

while True:
    if pygame.QUIT in [e.type for e in pygame.event.get()]:
        pygame.quit()
        break
    time.sleep(0.1)
    pts = (np.random.rand(10,2) * (640,320)).astype(int)
    c = (np.random.rand(3)*255).astype(int)
    screen.fill("black")
    pygame.draw.lines(screen, c, True, pts, 1)
    pygame.display.flip()

上面的代码中,lines用于生成随机直线,其5个参数中

  • screen可理解为绘制直线的画板
  • c即随机生成的三元组,表示颜色
  • True对应closed参数,表示生成的直线最后要封闭
  • pts即随机生成二元点集
  • 最后,1表示直线的宽度。

光线反射

有了直线工具,可以做一个光线反射动画,比如现有一点 x 0 , y 0 x_0, y_0 x0,y0,其出射角度为 θ \theta θ,则射线方程可写为

x = x 0 + k x t k x = cos ⁡ θ y = y 0 + k y t k x = sin ⁡ θ x=x_0+k_x t\quad k_x=\cos\theta\\ y=y_0+k_y t\quad k_x=\sin\theta x=x0+kxtkx=cosθy=y0+kytkx=sinθ

这个直线将于4个墙壁产生交点,根据 θ \theta θ的值,可判断具体的交点,具体代码如下

python 复制代码
def cross(x0, y0, kx, ky, w, h):
    pL = (0, y0-ky/kx*x0)
    pD = (x0-kx/ky*y0, 0)
    pR = (w, y0+ky/kx*(w-x0))
    pT = (x0+kx/ky*(h-y0), h)
    if kx>0 and ky>0:
        return pR if pR[1]<h else pT
    if kx>0 and ky<0:
        return pR if pR[1]>0  else pD
    if kx<0 and ky>0:
        return pL if pL[1]<h else pT
    if kx<0 and ky<0:
        return pL if pL[1]>0 else pD

在有了交点之后,可以得到新的角度。如果是在上下壁反射,则 k x k_x kx变号,否则 k y k_y ky变号。

python 复制代码
def getNewK(kx, ky, x1, w):
    flag = x1==0 or x1==w
    return (-kx, ky) if flag else (kx, -ky)

最后,是绘图逻辑

python 复制代码
pygame.init()
w, h = 640, 320
screen = pygame.display.set_mode((w, h))

pts = [np.random.rand(2)*(w, h)]
th = np.random.rand()*np.pi
kx, ky = np.cos(th), np.sin(th)

while True:
    if pygame.QUIT in [e.type for e in pygame.event.get()]:
        pygame.quit()
        break
    time.sleep(0.1)
    x,y = pts[-1]
    pt = cross(x,y, kx, ky, w, h)
    pts.append(pt)
    kx, ky = getNewK(kx, ky, pt[0], w)
    c = (np.random.rand(3)*255).astype(int)
    screen.fill("black")
    pygame.draw.lines(screen, c, False, pts, 1)
    pygame.display.flip()

效果如下

相关推荐
马优晨7 分钟前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
玉鸯1 小时前
Agent Hook:在概率推理之上,为 Agent 叠加确定性控制
python·langchain·agent
weixin_446260851 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
我的xiaodoujiao2 小时前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest
人邮异步社区2 小时前
怎么把C语言学到精通?
c语言·开发语言
qetfw2 小时前
MXU:Tauri 2 + React 的 MaaFramework 跨平台 GUI 源码
前端·python·react.js·前端框架·开源项目·效率工具
心平气和量大福大2 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai3 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
用户8356290780513 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python