如何解决在 python 龟中,当我想显示球的随机运动时,它们不会从我的屏幕边缘反弹
import turtle
import random
import time
我们确认球在屏幕左侧
def atLeftEdge(ball,screen_width):
if ball.xcor()<screen_width/2:
return True
else:
return False
我们确认球在右侧
def atRightEdge(ball,screen_width):
if ball.xcor()>screen_width/2:
return True
else:
return False
我们确认球在顶部边缘
def atTopEdge(balls,screen_height):
if ball.ycor()>screen_height/2:
return True
else:
return False
我们确认球在底部边缘
def atBottomEdge(balls,screen_height):
if ball.ycor()<-screen_height/2:
return True
else:
return False
现在球到达屏幕边缘时必须反弹
def bounceBall(ball,new_direction):
if new_direction=='left'or new_direction=='right':
new_heading=180-ball.heading()
elif new_direction=='up'or new_direction=='down':
new_heading=360-ball.heading()
return new_heading
def createBalls(num_balls):
balls=[]
for x in range(0,num_balls):
new_ball=turtle.Turtle()
new_ball.shape('circle')
new_ball.fillcolor('black')
new_ball.speed(0)
new_ball.penup()
new_ball.setheading(random.randint(1,359)) #random angle between 1 to 359
balls.append(new_ball)
return balls
程序从这里开始,这是程序的主要部分,我们从用户那里获取输入并调用所有函数
#------------------MAIN-------------------------------------------------
print("The program stimulates bouncing balls in a turtle screen"\
"for a specified number of seconds")
#TODO:create turtle graphics window object
#set up screen
screen_width=800
screen_height=600
turtle.setup(screen_width,screen_height)
#get reference to turtle window by calling Screen method
window=turtle.Screen()
window.title('Random balls on screen')
window.bgcolor('violet')
要求用户输入执行时间和球数
num_sec=int(input("enter no of seconds to run"))
num_balls=int(input("enter no of balls in sim"))
创建球
balls=createBalls(num_balls)
设置开始时间
start_time=time.time()
开始模拟
terminate=False
while not terminate:
for x in range(0,len(balls)):
balls[x].forward(40)
if atLeftEdge(balls[x],screen_width):
balls[x].setheading(bounceBall(balls[x],'right'))
elif atRightEdge(balls[x],'left'))
elif atTopEdge(balls[x],screen_height):
balls[x].setheading(bounceBall(balls[x],'down'))
elif atBottomEdge(balls[x],'up'))
if time.time()-start_time>num_sec:
terminate =True
#exit on close window
turtle.exitonclick()
解决方法
我已将 elif
更改为 if
,因为它们是独立事件。
if atLeftEdge(balls[x],screen_width):
balls[x].setheading(bounceBall(balls[x],'right'))
if atRightEdge(balls[x],'left'))
if atTopEdge(balls[x],screen_height):
balls[x].setheading(bounceBall(balls[x],'down'))
if atBottomEdge(balls[x],'up'))
同样在 atLeftEdge
函数中你需要这样写:
if ball.xcor()<-screen_width/2:
也在 atTopEdge
和 atBottomEdge
中,我想你的意思是
def atTopEdge (ball,screen_height) :
和
def atBottomEdge(ball,screen_height):
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。