[编程之美]用pygamezero生成的四边形运动轨迹
  • 板块灌水区
  • 楼主Wildchesse
  • 当前回复8
  • 已保存回复8
  • 发布时间2021/6/6 18:47
  • 上次更新2023/11/4 22:13:50
查看原帖
[编程之美]用pygamezero生成的四边形运动轨迹
362022
Wildchesse楼主2021/6/6 18:47

一分钟:

十分钟后..........

源码:

import pgzrun
from vec import *
import random

WIDTH = 600
HEIGHT = 440

BACK_COLOR = (0, 0, 0)
PEN_COLOR = (0, 200, 0)
class PointTail:
    def __init__(self):
        self.tail = []

    def UpdatePoint(self, x, y):
        for i in range(self.count - 2, -1, -1):
            self.tail[i + 1].x = self.tail[i].x
            self.tail[i + 1].y = self.tail[i].y
        self.tail[0].x = x
        self.tail[0].y = y

    def InitPoints(self, n):
        self.count = n
        self.vx = random.randint(-5, 5)
        self.vy = random.randint(-5, 5)
        px = random.randint(0, WIDTH - 1)
        py = random.randint(0, HEIGHT - 1)
        for i in range(self.count):
            self.tail.append(Vec2(px, py))

    def GetPoint(self, index):
        return self.tail[index]

    def Update(self):
        newX = self.tail[0].x + self.vx
        newY = self.tail[0].y + self.vy

        if newX >= WIDTH - 1:
            newX = WIDTH - 1
            self.vx *= -1
        elif newX <= 0:
            newX = 0
            self.vx *= -1

        if newY >= HEIGHT - 1:
            newY = HEIGHT - 1
            self.vy *= -1
        elif newY <= 0:
            newY = 0
            self.vy *= -1

        self.UpdatePoint(newX, newY)

pointCount = 4
p = []
for i in range(pointCount):
    pt = PointTail()
    pt.InitPoints(2000)
    p.append(pt)

def update():
    for i in range(0, pointCount):
        p[i].Update()

def draw():
    screen.clear()
    screen.fill(BACK_COLOR)

    for i in range(0, pointCount):
        for j in range(0, p[i].count):
            if i == pointCount - 1:
                screen.draw.line(p[i].GetPoint(j).raw_get(), p[0].GetPoint(j).raw_get(), PEN_COLOR)
            else:
                screen.draw.line(p[i].GetPoint(j).raw_get(), p[i + 1].GetPoint(j).raw_get(), PEN_COLOR)

pgzrun.go()

2021/6/6 18:47
加载中...