14
2024
11

python编程学习-一笔画关卡生成

学习python编程,在新东方少儿编程官网的自由创作平台做的一些作品。

可以在线运行,效果如下(在新页面中打开链接):

代码如下(用到平台自定义的xdf库):

from xdf import *
import math

W = 768
H = 1024
h0 = 60
ps = []
ls = []

def reset():
    ps.clear()
    ls.clear()
    refresh()
    pass
def trace():
    s = '[['+str(ps)+'],['+ str(ls)+']]'
    print(s)
    pass
text('点击清空重新开始', 0, h0, h0, 'red').tap = reset
text('点击完成输出结果', 0, H, h0, 'red').tap = trace

def ang2rad(ang):
    return math.pi * ang / 180
def rad2ang(rad):
    return 180 * rad / math.pi

class factory:
    def __init__(self, tp, co):
        self.tp = tp
        self.co = co
        self.arr = []
        self.pool = []
        pass
    def get(self):
        if len(self.pool):
            return self.initC(self.pool.pop())
        return self.initC(self.create())
    def initC(self, c):
        self.arr.append(c)
        c.front()
        c.show()
        return c
    def remove(self, c):
        c.hide()
        self.pool.append(c)
        self.arr.remove(c)
        pass
    def removeAll(self):
        for c in self.arr:
            c.hide()
        self.pool.extend(self.arr)
        self.arr.clear()
        pass
    def create(self):
        if self.tp == 'circle':
            return circle(0, 0, 10, self.co)
        if self.tp == 'line':
            return line(0, 0, 100, 100, 5, self.co)
        return None
    pass
facC = factory('circle', 'red')
facL = factory('line', 'black')

def tap():
    if y > h0 and y < H - h0:
        pushP(int(x), int(y))
        refresh()
        pass
    pass

def pushP(x, y):
    pi = getP(x, y)
    if pi >= 0:
        ls.append(pi)
    else:
        ls.append(len(ps))
        ps.append(x)
        ps.append(y)

def getP(x, y):
    for i in range(0, len(ps), 2):
        dx = x - ps[i]
        dy = y - ps[i+1]
        if dx*dx + dy*dy < 20*20:
            return i
    return -1

def setLine(li, x0, y0, x1, y1):
    dx = x1 - x0
    dy = y1 - y0
    sz = math.sqrt(dx * dx + dy * dy)
    rot = math.atan2(dy, dx)
    li.move(x0, y0)
    li.rotate(rad2ang(rot) + 90)
    li.size(sz)
    pass

def refresh():
    facC.removeAll()
    facL.removeAll()
    for i in range(1, len(ls)):
        x0 = ps[ls[i - 1]]
        y0 = ps[ls[i - 1] + 1]
        x1 = ps[ls[i]]
        y1 = ps[ls[i] + 1]
        setLine(facL.get(), x0, y0, x1, y1)
    for i in range(0, len(ps), 2):
        facC.get().move(ps[i], ps[i+1])



也可以下载代码,本地python环境运行(用pygame封装了xdf库)。



« 上一篇下一篇 »

相关文章:

python编程学习-华容道  (2024-11-14 16:43:25)

python编程学习-动画  (2024-11-14 16:39:37)

python编程学习-别踩白块  (2024-11-14 16:38:59)

python编程学习-俄罗斯方块  (2024-11-14 16:38:19)

python编程学习-井字棋  (2024-11-14 16:34:9)

python编程学习-五子棋  (2024-11-14 16:33:23)

python编程学习-乒乓  (2024-11-14 16:32:46)

python编程学习-一笔画  (2024-11-14 16:31:27)

python编程学习-woblox  (2024-11-14 16:30:47)

python编程学习-where-my-ice-cream  (2024-11-14 16:29:57)

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。