# Problem 2, HWK 3, PHY307 Fall 2002 # Race a yellow sphere, blue ring and white cube. Staggered by # a distance of 2 in the z direction, they breathtakingly race to the # right. # # The 3 objects are intially created, then their positions are # changed by adding a small amount to each objects' x position # in a loop, whose rate is controlled by the rate() statement. # # racefancy.py - same basic idea as race.py, except # - add a starter # - add labels # - make the track more symmetric about the origin, for easier spinning # - move the starting line down so doesn't intersect racer # - add a finish line # - make them stop when they cross the finish line # - spin the cube and ring as they run, using rotate from visual import * racelength = 4 # for bonus kicks, draw a starting and finish line startline = cylinder(axis=(0,0,4),radius=0.1,x=-racelength,y=-0.5,z=-2, color=color.green) finishline = cylinder(axis=(0,0,4),radius=0.1,x=racelength,y=-0.5,z=-2, color=color.red) # draw a starter - a cylinder with a spherical head starterbody = cylinder(axis=(0,1,0),radius=0.3, pos=(-racelength-1,-0.5,-2.5), color=color.magenta) starterhead = sphere(radius=0.3,pos=(-racelength-1,0.9,-2.5), color=color.magenta) starterlabel = label(pos=starterhead.pos, text='Approach the start', xoffset=20, yoffset=25, space=starterhead.radius, height=18, border=6) rate(0.15) # sleep about 7 seconds # bring on the racers racer1 = sphere(color=color.yellow, radius=0.5, z=-2, x=-racelength) racer2 = ring(color=color.blue, radius=0.5, z=0, x=-racelength) racer3 = box(color=color.white,z=2, x=-racelength) starterlabel.text='On your mark ...' rate(0.5) # sleep 2 seconds starterlabel.text='... get set ...' rate(0.5) starterlabel.text='Go!!!' # prevent autoscaling, so that motion can be seen more cleanly scene.autoscale=0 bouncy=0.5 nolabel1 = 1 nolabel2 = 1 nolabel3 = 1 while 1: rate(40) # move the racers, if they haven't reached the finish line if (racer1.x < racelength): racer1.x = racer1.x + 0.04 if (racer2.x < racelength): racer2.x = racer2.x + 0.03 racer2.rotate(angle=-0.03,axis=(0,0,1)) if (racer3.x < racelength): racer3.x = racer3.x + 0.02 racer3.rotate(angle=-0.02,axis=(0,0,1)) # if they have reached the finish line and have no label, give them one if (racer1.x >= racelength): if (nolabel1): t = 0 racer1.label = label(pos=racer1.pos, text='I win!!!', xoffset=20, yoffset=25, space=racer1.radius, height=18, border=6) # relabel starter's 'Go!' starterlabel.text = 'New record!' nolabel1 = 0 # the winner is ecstatic - move it and its label t = t + 0.06 racer1.y = sin(t)*bouncy # jump up and down for joy racer1.label.y = racer1.y if (racer2.x >= racelength and nolabel2): racer2.label = label(pos=racer2.pos, text='Second!', xoffset=20, yoffset=25, space=racer2.radius, height=18, border=6) nolabel2 = 0 if (racer3.x >= racelength and nolabel3): racer3.label = label(pos=racer3.pos, text='Third :(', xoffset=20, yoffset=25, space=racer3.length, height=18, border=6) nolabel3 = 0