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],screen_width):
balls[x].setheading(bounceBall(balls[x],'left'))
elif atTopEdge(balls[x],screen_height):
balls[x].setheading(bounceBall(balls[x],'down'))
elif atBottomEdge(balls[x],screen_height):
balls[x].setheading(bounceBall(balls[x],'up'))
if time.time()-start_time>num_sec:
terminate =True
#exit on close window
turtle.exitonclick()
Я изменил elif
s на if
s, так как это независимые события.
if atLeftEdge(balls[x],screen_width):
balls[x].setheading(bounceBall(balls[x],'right'))
if atRightEdge(balls[x],screen_width):
balls[x].setheading(bounceBall(balls[x],'left'))
if atTopEdge(balls[x],screen_height):
balls[x].setheading(bounceBall(balls[x],'down'))
if atBottomEdge(balls[x],screen_height):
balls[x].setheading(bounceBall(balls[x],'up'))
также в функции atLeftEdge
вам нужно написать свой if следующим образом:
if ball.xcor()<-screen_width/2:
также в atTopEdge
и atBottomEdge
Я думаю, вы имели в виду
def atTopEdge (ball , screen_height) :
и
def atBottomEdge(ball , screen_height):
несвязанный - вы можете переписать свой тест, чтобы он был:
def atLeftEdge(ball,screen_width): return ball.xcor() < screen_width/2
- похожим на другие. Сравнение уже возвращает логическое значение, не нужно егоif ...: return True else: return False