明天要做第四周的mini-project ,今天把老师的演示程序打出来练习一下。
小小做了一些修改,让圆球碰到边界时可以变色,也在左上角显示了圆球的当前速度,
这样用箭头控制它的速度时,心里会比较有数。
# control the velocity of a ball using the arrow keys
import simplegui
# Initialize globals
WIDTH=600
HEIGHT=400
BALL_RADIUS=20
ball_pos=[WIDTH/2,HEIGHT/2]
Vel=[-3,1]
color="Brown"
# define event handlers
def draw(canvas):
global color
#update ball positon
ball_pos[0]+=Vel[0]
ball_pos[1]+=Vel[1]
# collide and reflect off of left
if ball_pos[0]<=BALL_RADIUS:
Vel[0]=-Vel[0]
color="Blue"
elif ball_pos[0]>=WIDTH-BALL_RADIUS:
Vel[0]=-Vel[0]
color="Teal"
elif ball_pos[1]<=BALL_RADIUS:
Vel[1]=-Vel[1]
color="Brown"
elif ball_pos[1]>=HEIGHT-BALL_RADIUS:
Vel[1]=-Vel[1]
color="Grey"
# draw ball
canvas.draw_circle(ball_pos,BALL_RADIUS,2,color,color)
# draw text
canvas.draw_text("Current Velocity:"+str(Vel),[20,30],15,"White")
def keydown(key):
acc=1
if key==simplegui.KEY_MAP["left"]:
Vel[0] -=acc
elif key==simplegui.KEY_MAP["right"]:
Vel[0] +=acc
elif key==simplegui.KEY_MAP["up"]:
Vel[1] -=acc
elif key==simplegui.KEY_MAP["down"]:
Vel[1] +=acc
# create frame
frame=simplegui.create_frame("Motion",WIDTH,HEIGHT)
# register event handlers
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
#frame start
frame.start()