莱斯大学Python课程第四周演示程序

明天要做第四周的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()	


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值