简体   繁体   English

在python中没有if的弹跳球

[英]Bouncing ball without if in python

How can I edit my program without if statement?如何在没有if语句的情况下编辑我的程序?

from visual import *

display(title='BasicEdit', x=0, y=0, fullscreen=True,
        center=(0,0,0), range=(10,10,10),
        background=(0,0,0))
x_axis = arrow(pos=(0,0,0), axis = vector(3,0,0), color=color.green)
y_axis = arrow (pos=(0,0,0), axis = vector(0,3,0), color=color.red)
z_axis = arrow(pos=(0,0,0), axis = vector(0,0,3), color=color.cyan)
ball = sphere(pos=(0,4,0), radius = 0.4, color=color.red)
ball.velocity = vector(0,-1,0)
ground = box(pos = (0,-0.1,0), lenght = 50, height = 0.1, width = 50)

dt = 0.01
while 1:
    rate(100)
    ball.pos = ball.pos + ball.velocity*dt
    if ball.y < 1:
        ball.velocity.y = -ball.velocity.y
    else:
        ball.velocity.y = ball.velocity.y - 9.8*dt

I think you want to remove your if/else condition from your code keeping the same logic, you may use and/or combination for that.我认为您想从保持相同逻辑的代码中删除if/else条件,您可以为此使用and/or组合。 For example, for your code:例如,对于您的代码:

if ball.y < 1:
    ball.velocity.y = -ball.velocity.y
else:
    ball.velocity.y = ball.velocity.y - 9.8 * dt

without using if/else it could be written as:不使用if/else可以写成:

ball.velocity.y = (ball.y < 1 and -ball.velocity.y) or (ball.velocity.y - 9.8 * dt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM