如何修复:这个工厂函数只工作一次

How to fix: This factory function only works once

这个函数只能用一次,然后就不能再用了。有人能告诉我我做错了什么吗?

from vpython import *
def create_cube(pos,size,front,back,left,right,bottom,top):
    c = [ pyramid(pos=pos-vector(0.5,0,0),size=size,color=left),
    pyramid(pos=pos+vector(0.5,0,0),size=size,color=right).rotate(angle=radians(180),axis=vector(0,1,0)),
    pyramid(pos=pos+vector(0,0,0.5),size=size,color=front).rotate(angle=radians(90),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0,0.5),size=size,color=back).rotate(angle=radians(270),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0.5,0),size=size,color=bottom).rotate(angle=radians(90),axis=vector(0,0,1)),
    pyramid(pos=pos+vector(0,0.5,0),size=size,color=top).rotate(angle=radians(270),axis=vector(0,0,1)),
    box(pos=pos,size = vector(0.9,0.9,0.9),color=color.black)]
    return compound(c)

topleftfrontcorner = create_cube(vector(-1,1,1),vector(0.5,0.90,0.90),color.red,color.black,color.blue,color.black,color.black,color.yellow)
topmiddlefrontside = create_cube(vector(0,0,0),vector(0.5,0.90,0.90),color.red,color.black,color.black,color.black,color.black,color.yellow)

我希望这个函数在我每次调用它时都能输出一个自定义 'cube' 而不是一次。

您应该 return c,并在 topleftfrontcornertopmiddlefrontside 上使用 compound:

from vpython import *
def create_cube(pos,size,front,back,left,right,bottom,top):
    c = [ pyramid(pos=pos-vector(0.5,0,0),size=size,color=left),
    pyramid(pos=pos+vector(0.5,0,0),size=size,color=right).rotate(angle=radians(180),axis=vector(0,1,0)),
    pyramid(pos=pos+vector(0,0,0.5),size=size,color=front).rotate(angle=radians(90),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0,0.5),size=size,color=back).rotate(angle=radians(270),axis=vector(0,1,0)),
    pyramid(pos=pos-vector(0,0.5,0),size=size,color=bottom).rotate(angle=radians(90),axis=vector(0,0,1)),
    pyramid(pos=pos+vector(0,0.5,0),size=size,color=top).rotate(angle=radians(270),axis=vector(0,0,1)),
    box(pos=pos,size = vector(0.9,0.9,0.9),color=color.black)]
    return c

topleftfrontcorner = create_cube(vector(-1,1,1),vector(0.5,0.90,0.90),color.red,color.black,color.blue,color.black,color.black,color.yellow)
topmiddlefrontside = create_cube(vector(0,0,0),vector(0.5,0.90,0.90),color.red,color.black,color.black,color.black,color.black,color.yellow)
compound(topleftfrontcorner, topmiddlefrontside)

这样做给了我:

也许更熟悉vpython的人可以解释更多,但一般来说,创建立方体和渲染立方体是有区别的。您在代码片段中看不到两个立方体的原因是程序仍在呈现第一个立方体(阻塞操作),甚至没有评估第二个函数调用。您可以通过在两个函数调用之间放置 print("hello!") 来了解情况; "hello!" 永远不会打印,因为程序仍在忙于渲染 topleftfrontcorner

在更新的代码片段中,我们构建了两个立方体,然后同时渲染它们。