小球碰到四边被弹回,初学者日常
import turtle
import random
import time
#获得当前窗口的对象
screen=turtle.Screen()
#设置窗口标题
screen.title('Crazy pinball')
screen_width=1000
screen_hight=800
screen.setup(screen_width,screen_hight)
#载入背景图片
screen.bgpic('D:\Saved Pictures/1.png')
colors=['pink','red','blue','green','yellow','skyblue','navy','orange','white','purple']
colors=colors*2
balls=[]
turtle.tracer(False)
for c in colors:
temp=turtle.Turtle()
temp.shape('circle')
temp.color(c)
temp.penup()
temp.setheading(random.randint(0,360))
balls.append(temp)
turtle.tracer(True)
def ballmove(ball):
step=5
heading=ball.heading()
#撞到右边
if ball.xcor()+15>=(screen_width/2):
if heading>=0 and heading<90:
s=90-heading
h=90+s
ball.setheading(h)
else:
s=270+heading
h=270-s
ball.setheading(h)
#撞到左边
elif ball.xcor()-15<=-(screen_width/2):
if heading>90 and heading<=180:
s=heading-90
h=90-s
ball.setheading(h)
else:
s=270-heading
h=270+s
ball.setheading(h)
#撞到上面
elif ball.ycor()+15>=screen_hight/2:
if heading >= 0 and heading < 90:
s=heading
h=-s
ball.setheading(h)
else:
s=180-heading
h=180+s
ball.setheading(h)
#撞到下面
elif ball.ycor()-15<=-(screen_hight/2):
if heading>90 and heading<=180:
s=heading-180
h=180-s
ball.setheading(h)
else:
s =-heading
h = s
ball.setheading(h)
ball.forward(step)
step=5
try:
while True:
turtle.tracer(False)
for ball in balls:
ball.forward(step)
ballmove(ball)
time.sleep(0.017)
screen_width=turtle.window_width()
screen_hight=turtle.window_height()
turtle.tracer(True)
except:
print('quit')