Как вызвать функцию внутри другой функции в vPython - PullRequest
0 голосов
/ 18 мая 2018

ОБНОВЛЕНИЕ: игнорировать главный вопрос.Я понял это (спасибо Гилчу).Единственное, что мне нужно знать сейчас, это второй вопрос, приведенный ниже ... Как вызвать отдельную функцию внутри другой функции.

Когда оператор while закончен и я сброшен, я больше не могу перемещать шарпотому что цикл while не будет инициирован заново, поэтому я не могу повторно поднять мяч, чтобы снова упасть.Я должен полностью перезапустить код.Я новичок в vpython (делаю это для класса физики), и я не могу найти способ перезапустить цикл while (или как-то еще это исправить).

Я почти уверенэто происходит потому, что цикл while заканчивается, а затем, когда положение и скорость мяча сбрасываются, цикл while не запускается заново, поэтому я не могу двигать мяч, но я не уверен, как это сделать.Спасибо всем, кто может помочь.

Код:

GlowScript 2.7 VPython
#Start without running
running = False
#when "Run" is initiated
def Run(b):
    #Bring in running variable from outside
    global running
    #When Run/Pause Button is pressed, switch between running and pausing the program
    running = not running
    #When run button is pressed, change text to "Pause"
    if running: bbutton.text = "Pause"
    #When pause button is pressed, change text to "Run"
    else: bbutton.text = "Run"

#Create Run Button above program
bbutton = button(text="Run", pos=scene.title_anchor, bind=Run)

#When "Reset" is initiated
def Reset(c):
    #Bring in t and ball variables from outside
    global t, ball
    #Set back to time = 0 (when reset)
    t = 0
    #Reset ball's position to initial position (when reset)
    ball.pos = vec(0,2,0)
    #resets ball's velocity to initial velocity (when reset)
    ball.vel = vec(0,0,0)

#Create reset button above program
cbutton = button(text="Reset", pos=scene.title_anchor, bind=Reset)

#Create ground
ground = box(pos=vec(0,0,0), size=vec(10,0.2,10))
#Create ball
ball = sphere(pos=vec(0,2,0), radius=0.4, color=color.yellow)
#Initial Velocity
ball.vel = vec(0,0,0)
#Acceleration (free-falling)
g = -9.8
#Initial Time
t = 0
#Time increase per frame
deltat = 0.01

#Turns "drag" condition to false to begin
drag = False
#Initial mouse position
R = vec(0,0,0)
#When you click
scene.bind("mousedown", def():
    #Bring in drag variable from outside
    global drag
    #Set drag to true on mouseclick
    drag = True

    #When you release click
    scene.bind("mouseup", def():
        #Bring in drag variable from outside
        global drag
        #Set drag to false when you release click
        drag = False
    )
)

#While True (the program is running) and the ball is higher than slightly under the ground
#If the second condition is not there, the ball will continually go down through the ground forever
#The second condition stops the ball once it begins going underneath the platform, so it looks normal

while True and ball.pos.y > ground.pos.y + 0.48:
    #Slow down program
    rate(100)
    #When the drag condition is true (When mouse is clicked on ball)...
    if drag:
        #Set R to position of mouse
        R = scene.mouse.pos
        #Set ball position to R (position of mouse) -- allows the ball to be     dragged (changes ball position)
        ball.pos = R
    #When the program is running (run button is pressed)...
    if running:
        #Update ball velocity
        #   v      =     v0     + a (change in time)
        ball.vel.y = ball.vel.y + g*deltat
        #Update position velocity
        #   x    =    x0    +    v    *(change in time)
        ball.pos = ball.pos + ball.vel*deltat
        #When the ball hits the surface of the ground...
        if (ball.pos.y <= ground.pos.y + 0.5):
            #Change the sign of the velocity (to go back up)
            ball.vel.y = -ball.vel.y
        if (ball.pos.y < ground.pos.y +0.48):
            break
        #Update time
        t = t + deltat

ОБНОВЛЕНИЕ: Я включил цикл while в функцию Initiate, но не знаю, как добавить функцию Initiate в функцию Reset...

Новый код (только с соответствующим кодом): #OTHER CODE

def Reset(c):
    #Bring in t and ball variables from outside
    global t, ball
    #Set back to time = 0 (when reset)
    t = 0
    #Reset ball's position to initial position (when reset)
    ball.pos = vec(0,2,0)
    #resets ball's velocity to initial velocity (when reset)
    ball.vel = vec(0,0,0)

    #Initiate() -- HOW DO I RUN INITIATE INSIDE THE RESET FUNCTION**

#OTHER CODE

Initiate()    

def Initiate():
    global ground, ball, g, t, deltat, drag, R

    while True and ball.pos.y > ground.pos.y + 0.48:
        #Slow down program
        rate(100)
        #When the drag condition is true (When mouse is clicked on ball)...
        if drag:
            #Set R to position of mouse
            R = scene.mouse.pos
            #Set ball position to R (position of mouse) -- allows the ball to be dragged (changes ball position)
            ball.pos = R
        #When the program is running (run button is pressed)...
        if running:
            #Update ball velocity
            #   v      =     v0     + a (change in time)
            ball.vel.y = ball.vel.y + g*deltat
            #Update position velocity
            #   x    =    x0    +    v    *(change in time)
            ball.pos = ball.pos + ball.vel*deltat
            #When the ball hits the surface of the ground...
            if (ball.pos.y <= ground.pos.y + 0.5):
                #Change the sign of the velocity (to go back up)
                ball.vel.y = -ball.vel.y
            if (ball.pos.y < ground.pos.y +0.48):
                break
            #Update time
            t = t + deltat

Ответы [ 2 ]

0 голосов
/ 18 мая 2018

Перейдите на vpython.org и нажмите на ссылку на форум vpython или форум glowscript и задайте свой вопрос там.

0 голосов
/ 18 мая 2018

Попробуйте поместить цикл while внутри функции def и запустить его, вызвав функцию.Затем вы можете снова вызвать функцию, чтобы перезапустить цикл.

...