Пример #1
0
def main():
    win = gr.GraphWin( 'balls colliding', 500, 500, False )

    ball1 = pho.Ball( win, 20 )
    ball2 = pho.Ball( win, 20 )
    ball1.setPosition( [200, 200] )
    ball2.setPosition( [300, 200] )

    # set up velocity and acceleration so they collide
    ball1.setVelocity( [200, 200] )
    ball2.setVelocity( [-200, 200] )
    ball1.setAcceleration( [0, -200] )
    ball2.setAcceleration( [0, -200] )
    ball1.draw()
    ball2.draw()

    txt = gr.Text( gr.Point( 250, 50), "Click to continue" )
    txt.setSize( 16 )
    txt.draw(win)
    win.getMouse()

    # loop for some time and check for collisions
    dt = 0.01
    for frame in range(120):
        if not coll.collision_ball_ball( ball1, ball2, dt ):
            ball1.update(dt)
        else:
            txt.setText( "Boom!" )

        if not coll.collision_ball_ball( ball2, ball1, dt ):
            ball2.update(dt)
        
        win.update()
        time.sleep(0.5*dt)
        if win.checkMouse() != None:
            break

    txt.setText('Click to quit')
    win.getMouse()

    txt.setText('See ya')
    win.update()
    time.sleep(0.2)
    
    win.close()
Пример #2
0
def initializeSprite(win):

    sprite = PO.Ball(win, 20, 30, 2)

    sprite.Color('black')

    sprite.setVelocity([0, 0])
    sprite.setAcceleration([0, -15])

    #sprite.draw()

    return sprite
Пример #3
0
def drawAsteroids(win):
    '''
    draws 5 asteroids into the scene, giving them random
    velocities, force and colour. Returns the list of asteroids
    '''
    asteroids = []
    
    for i in range(5):
        asteroid = pho.Ball(win, random.randint(50,60), random.randint(10,40), 1, random.randint(1,3))
        asteroid.setFill(random.choice(['red', 'green', 'yellow']))
        asteroid.setVelocity([-0.1,random.random()])
        asteroid.setForce([-0.1, random.randint(-1, 1)])
        asteroid.setElasticity(0.9)
        asteroids.append(asteroid)
        asteroid.draw()
        play.append(asteroid)
    return asteroids
Пример #4
0
def main():
    # variables
    key = ''
    dt = 0.02
    frame = 0
    gamma = 100
    delta = 0.5
    winWidth = 50
    winHeight = 50
    counter = 0
    # start screen, ie state is 0
    # make a window
    win = gr.GraphWin('Galaxy Impact', 500, 500, False)
    win.setBackground("black")
    quit = False
    state = 0
    if state == 0:
        ship = pho.Ship(win, 8, 40)
        ship1 = pho.Ship(win, 43, 40)
        ship.setRotVelocity(30)
        ship1.setRotVelocity(30)
        title = gr.Text(gr.Point(250, 100), "Galaxy Impact")
        title.setFill('red')
        title.setSize(36)
        # instruction to start text
        instruction = gr.Text(gr.Point(250, 200), "click start to begin")
        instruction.setFill('orangered')
        instruction.setSize(20)
        begin = pho.Block(win, 25, 25, 10, 6, coloring='indianred')
        begins = gr.Text(gr.Point(250, 250), "start")
        begins.setSize(15)
        close = pho.Block(win, 25, 15, 10, 6, coloring='indianred')
        closes = gr.Text(gr.Point(250, 350), "close")
        closes.setSize(15)
        instructions = gr.Text(
            gr.Point(250, 420),
            " INSTRUCTIONS: \n space to shoot \n up to go up \ left to go left, right to go right \n down to go down"
        )
        instructions.setFill('red')
        starts = [closes, instruction, title, begins, instructions]
        boxes = [begin, close, ship, ship1]
        # draw all the boxes
        for box in boxes:
            box.draw()
    # draw all the text
        for word in starts:
            word.draw(win)
#wait for a mouse click on start to start
        while True:
            ship.update(dt)
            ship1.update(dt)
            event = win.checkMouse()
            if event != None and event.x < 300 and event.x > 200 and event.y > 220 and event.y < 280:
                state = 1
                break
            elif event != None and event.x < 300 and event.x > 200 and event.y > 320 and event.y < 380:
                win.close()
### main phase ie state is 1
# make ship, draw it,
    ship = pho.Ship(win, 25, 5)
    bullet = pho.Ball(win, -10, -10)
    ship.setAngle(90)
    old_rotV = ship.getRotVelocity()
    gamma = 100
    delta = 0.5
    winWidth = 50
    winHeight = 50
    bullets = []
    rains = []
    if state == 1:
        # undraw all from start screen
        for word in starts:
            word.undraw()
    # undraw all the boxes
        for box in boxes:
            box.undraw()
        win.setBackground("gray6")
        # draw objects
        ship.draw()
        while state == 1:
            #scores
            score = gr.Text(gr.Point(450, 50), "SCORE : %d" % counter)
            score.setSize(18)
            score.setFill("white")
            key = win.checkKey()
            # raining
            rain = pho.Ball(win,
                            random.randint(0, 50),
                            random.randint(45, 50),
                            radius=1)
            rain.setVelocity([random.randint(-5, 3), random.randint(-10, -5)])
            # draw
            if frame % 50 == 0:
                rain.draw()
                rains.append(rain)
        # check for collisions
            collided = False
            #			for item, go in zip(rains, bullets): #thought this could help double loop
            # if the bullet hits rain, undraw both ,and increment score
            for item in rains:
                if coll.collision(item, bullet, dt) == True:
                    print "S"
                    collided == True
                    item.undraw()
                    bullet.undraw()
# 					counter+=1
# 					score.undraw()
# 				#	win.update()
# 					score.draw(win)
#	if collided == False:
#rain.update(dt)
#bullet.update(dt)
            for item in bullets:
                if coll.collision(item, rain, dt) == True:
                    print "m"
                    collided == True
                    item.undraw()
                    rain.undraw()
    # 				counter+=1
# 					score.undraw()
# 				#	win.update()
# 					score.draw(win)
#if collided == False:
#rain.update(dt)
#bullet.update(dt)
# if rain hits spaceship, then you die
            for item in rains:
                z = item.getPosition()
                # scores if the rain doesnt touch, and goes down, not to the side :(
                if z[1] < 0:
                    counter += 1
                if coll.collision(item, ship, dt) == True:
                    collided == True
                    # make ship red
                    ship.vis[0].setFill("red")
                    ship.setFlickerOn()
                    time.sleep(0.001)
                    state = 2

# update world
            ship.update(dt)
            for x in bullets:
                x.update(dt)
            for x in rains:
                x.update(dt)
# user interface
            a = ship.getAngle()
            theta = a * math.pi / 180
            cth = math.cos(theta)
            sth = math.sin(theta)
            p = ship.getPosition()
            v = ship.getVelocity()
            g = bullet.getPosition()
            # movement
            if key == 'Up':
                p[1] += 1
                ship.setPosition(p)
                ship.setFlickerOn()
            if key == 'Down':
                p[1] -= 1
                ship.setPosition(p)
                ship.setFlickerOn()
            if key == 'Left':
                p[0] -= 1
                ship.setPosition(p)
                ship.setFlickerOn()
            if key == 'Right':
                p[0] += 1
                ship.setPosition(p)
                ship.setFlickerOn()
#	shoot bullets
            if key == 'space':
                b = 4
                bullet = pho.Ball(win, p[0], p[1], radius=0.5)
                # too much flick...though I could end up using it
                bullet.setVelocity([b * cth, b * sth])
                bullet.draw()
                bullets.append(bullet)
    # end game conditions
            if key == "q":
                state = 2
        # wrap the window
            moveit = False
            p = list(ship.getPosition())
            if p[0] < 0:
                p[0] += winWidth
                moveit = True
            elif p[0] > winWidth:
                p[0] -= winWidth
                moveit = True
            if p[1] < 0:
                p[1] += winHeight
                moveit = True
            elif p[1] > winHeight:
                p[1] -= winHeight
                moveit = True
            if moveit:
                ship.setPosition(p)
                moveit = False
        # update visualization
            if frame % 10 == 0:
                win.update()
                time.sleep(dt * 0.5)
            frame += 1

# end screen ie state == 2

    if state == 2:
        win.setBackground("red")
        ship.undraw()
        # undraw all from main screen
        for rain in rains:
            rain.undraw()
    # undraw all the boxes
        for bullet in bullets:
            bullet.undraw()
    # instruction to start text
        restart = gr.Text(gr.Point(250, 300), "press start to restart")
        restart.setFill('black')
        restart.setSize(20)
        # title of game:
        title = gr.Text(gr.Point(250, 100), "Galaxy Impact")
        title.setFill('black')
        title.setSize(36)
        # restart
        begin = pho.Block(win, 25, 25, 10, 6, coloring='brown4')
        begins = gr.Text(gr.Point(250, 250), "restart")
        begins.setSize(15)
        begins.setFill('white')
        begin.draw()
        gameover = gr.Text(gr.Point(250, 450), "GAME OVER")
        gameover.setStyle('bold italic')
        gameover.setSize(30)
        score = gr.Text(gr.Point(250, 350), "SCORE : %d" % counter)
        score.setSize(28)
        score.setStyle('bold')
        # draw everything
        ending = [restart, begins, title, gameover, score]
        for word in ending:
            word.draw(win)


#wait for a mouse click on start to restart
        while True:
            event = win.checkMouse()
            key = win.checkKey()
            if key == 'q':
                win.close()

            if event != None and event.x < 300 and event.x > 200 and event.y > 220 and event.y < 280:
                state = 0
                win.close()
                main()
                break
    # all done
        if quit == True:
            win.close()
Пример #5
0
def main():
	##### ASKS USER FOR HP VALUE #####
	hp = int(input("How much HP do you want for your ship?\n"))
	
	
	win = gr.GraphWin( "Space Invaders", 500, 800, False)
	state = 0
	
	#### LOOPING TO CHECK FOR DIFFERENT STATES ####
	while state != '':
		
		##### START SCREEN ########################################################################
		dt = 0.008
		bgm = False
		drawn = False
		while state == 0:
			if drawn == False:
				visualship = pho.RotShip(win, 25, 50)
				visualship.draw()
		
				wordplace1 = gr.Point( 250, 200 )
				startingwords1 = gr.Text(wordplace1, "SPACE INVADERS")
				startingwords1.setSize(36)
				startingwords1.setFace('courier')
				startingwords1.draw(win)
		
				wordplace2 = gr.Point( 250, 500 )
				words2 = "PRESS SPACE TO PLAY"
				startingwords2 = gr.Text(wordplace2, words2)
				startingwords2.setSize(36)
				startingwords2.setFace('courier')
				startingwords2.draw(win)
				
				startingwords3 = gr.Text(gr.Point(250, 600), "Use the Left and Right Arrow keys to move" + "\n" +"and use the space bar to shoot!")
				startingwords3.setSize(20)
				startingwords3.setFace('courier')
				startingwords3.draw(win)
				
				drawn = True
			else:		
				pass
		
			visualship.update(0.003)
			key = win.checkKey()
			if key == 'space':
				startingwords1.undraw()
				startingwords2.undraw()
				state = 1
		
			elif key == 'q':
				state = 3
				break
		##################################################################################
	
	
		##################################################################################
		##### MAIN PHASE #################################################################
		if state == 1:
			###### REGULATES BGM WHEN STATE GOES BACK TO MAIN PHASE
			if bgm == False:
				os.system("afplay ./music/bgm.mp3 &")
				bgm = True
			else:
				pass
			
			#### ALL OBJECTS SET HERE (EXCEPT FOR ENEMIES)
			ceiling = pho.Floor(win, 0, 80, 50, 15, 'yellow')
			ship = pho.Ship(win, 5, 5, 2, 2, healthcounter = hp)
			ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, 'yellow')
			enemyball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 3, 3, 'red')
			
			####  MOVING BACKGROUND
			background = pho.Floor(win, 0, 25, 50, 120, 'black')
			stars = []
			starmaking = True
			while starmaking:
				star = pho.Ball( win, random.randrange(0, 50, 2), random.randrange(0, 1000, 2), 0.1, 0.1, 'white')
				star.setVelocity( [0, -100] )
				stars.append( star )
				if len(stars) == 500:
					starmaking = False
			
			#### DRAWING THE OBJECTS HERE
			background.draw()
			for starmade in stars:
				starmade.draw()
			ceiling.draw()
			ship.draw()
	
			#####  SET ALL NECESSARY VARIABLES HERE #####
			########################################################################
			######	int variables###### 	
			frame = 0
			time1 = 0.
			time2 = 0.
			time3 = 0.
			time4 = 0.
			invincibletimer = 0
			bigshottimer = 0
			score = 0
			LEVEL = 1
			
			#### list variables ###
			colors = ['white','salmon2','orange','pink','green','yellow','red']
			enemies = []
			ballList = []
			enemyballList = []
			newballs = []
			newenemyballs = []
			hit1enemies = []
			hit2enemies = []
			deadenemies = []
			
			### booleans ####
			newtime = True
			invincible = False
			shipflash = False
			spawn = True
			bigshots = False
			bossbattle = True
			lagcheck = True
			shot = False
			leveldrawn = False
			start = False
			minibattle = True
			toomany = False
			
			#### other variable
			health = ship.healthcounter
			key = ''
			
			#### DRAWING THE FIRST HEALTH AND SCORE
			scorefunc(win, score)
			healthfunc(win, health)

			##### STARTING THE MAIN LOOP OF MINIBATTLE ###################################
			while state == 1 and minibattle == True:
				key = win.checkKey()
				#print 'minibattle'
				
				##### ALL UPDATE FUNC ####
				ship.update(dt)
				for i in ballList:
					i.update(dt)
				for j in newenemyballs:
					j.update(dt)
				for k in enemies:
					k.update(dt)
				for l in stars:
					l.update(dt)
				
				### SHIP UPGRADES ######
				#####  times the duration of the invincible upgrade
				##### invincible timing: basically invincibletimer gets incremented every time 
				#### through this while loop when invincible is assigned to True
				###   after 200 loops, invincibletimer is set to 0 and invicinble is set to False
				if invincible:
					invincibletimer += 1
					if invincibletimer > 200:
						invincible = False
						invincibletimer =0
						invincibletext.setTextColor('black')
				#### visual effect for when ship is invincible, draws and undraws one after another
				####  every time through the while loop by using booleans
				if invincible == True:
					if shipflash == False:
						ship.undraw()
						shipflash = True
					else:
						ship.draw()
						shipflash = False
				
				##### times the duration of the bigshots upgrade
				if bigshots:
					bigshottimer += 1
					if bigshottimer > 200:
						bigshots = False
						bigshottimer =0
						bigshottext.setTextColor('black')
				
				######################################################################
				######### MOVING SHIP WITH USER INPUT
				# move ship with user input
				if key == 'Left':
					ship.setVelocity( [-90, 0 ] )
					ship.setFlickerOn()
			
				if key == 'Right':
					ship.setVelocity( [90, 0 ] )
					ship.setFlickerOn()
					
				# ship boundaries
				if ship.getPosition()[0] > 50:
					ship.setVelocity( [-30, 0] )
				if ship.getPosition()[0] < 0:
					ship.setVelocity( [30, 0] )
	
				# shoot balls from the ship WITH USER INPUT
				##### REGUALTES THE NUMBER OF BALLS BEING SHOT AT A TIME 
				##### made a self.undrawn field in the physics_objects.py file 
				#### and made it be assigned to True when self.undrawn() is called and vice versa
				#### ALSO ADDED SOUND EFFECT BY USING os package
				if key == 'space':
					if ball.undrawn == True:	
						if bigshots == False:
							ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, random.choice(colors))
						else:
							ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 5, 5, random.choice(colors))
						ballList.append( ball )
						ball.setVelocity( [1,60])
						ball.draw()
						os.system("afplay " + "./music/shoot.wav" + "&")
					else:
						pass
				
				######################################################################
				
				
				# undraw the ball when it gets out of bounds
				if ball.getPosition()[1] > 70:
					ball.undraw()
#					ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, 'yellow')
				# 	print "undrawn!"
				else:
					newballs.append( ball )
		#		print ball.getPosition()[1]
			

				##########################################################################
			#ENEMY SPAWNING ZONE
				# spawn new enemy every 1 seconds
				if newtime == True:
					time1 = time.time()
				else:
					time2 = time.time()
	
				if time2 - time1 >= 1:
					spawn = True
					newtime = True
				else:
					newtime = False
				
				##### WROTE TO SOLVE LAGGING PROBLEM
				# every 39 seconds increments the time step (dt) so that it looks like it 
				# isn't lagging
				if lagcheck == True:
					time3 = int(time.time())
				else:
					time4 = int(time.time())
				if (time4 - time3) % 40 == 39:
					dt += 0.01
					lagcheck = True
				else:
					lagcheck = False
				
				######################################################################
				
				# regulating number of enemies
				if len(enemies) > 8:
					toomany = True
				else:
					toomany = False
				
				######################################################################
				# the actual spawning part
				if toomany == True:
					pass
				else:
					if spawn == True:
							if random.random() < 0.3:
								enemy = pho.Ship(win, 10, 10, 10, 10, angle = 270., dangle = 270., hit1 = False)	
							elif random.random() < 0.2:
								enemy = pho.Ship(win, 1, 1, 1, 1, angle = 270., dangle = 270., hit1 = False)
							elif random.random() < 0.1:
								enemy = pho.Ship(win, 1, 1, 2, 2, angle = 270., dangle = 270., hit1 = False)
# 							elif score % 31 == 5:
# 								boss = pho.Ship(win, 1, 1, 12, 12, angle = 270., dangle = 270., hit1 = False, hit2 = True, healthcounter = 500)
# 								bossbattle = True
# 								enemies.append( boss )
# 								boss.draw()
# 								boss.setPosition( [ 25, 60 ] )
# 								boss.setVelocity( [0, -30] )
							else:
								enemy = pho.Ship(win, 5, 5, 5, 5, angle = 270., dangle = 270., hit1 = False)
							enemies.append( enemy )
							
							enemy.draw()

							enemy.setPosition( [random.randrange(20, 45, 1), random.randrange(20, 55, 1 )])
							
							enemy.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])])
							spawn = False
				
				##########################################################################
			
			
			###### ENEMY MOVEMENT CONTROL AND ENEMY BALL SHOOTING 
				for badguy in enemies:
					if badguy.getPosition()[0] > 50:
						badguy.setVelocity( [random.randrange(-60, -40, 1), random.randrange(-30, 30, 10 )] )
					if badguy.getPosition()[0] < 0:
						badguy.setVelocity( [random.randrange(40, 60, 1), random.randrange(-30, 30, 10 )] )	
					if badguy.getPosition()[1] > 65:
						badguy.setVelocity( [random.randrange(-30, 30, 10), random.randrange(-60, -40, 1 )] )
					if badguy.getPosition()[1] < 20:
						badguy.setVelocity( [random.randrange(-30, 30, 1), random.randrange(40, 60, 1 )] )
					if random.random() < 0.05:
						badguy.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])] )
					
					# ENEMY SHOOTING BALL
					if random.random() < 0.02:
						enemyball = pho.Ball(win, badguy.getPosition()[0], badguy.getPosition()[1] - 4, 2, 2, 'red')
						enemyballList.append( enemyball )
						enemyball.setVelocity( [0,-70])
			#			print ship.getPosition()[0], ship.getPosition()[1]
						enemyball.draw()
			#			print "hi"
		
		###################################################################################

		
		#################################################################################
				# COLLISIONS AND UNDRAWING
				## ENEMY AND SHIP BALL
					if collision.collision( ball, badguy, dt):
						ball.undraw()
						ballList.remove(ball)
						
						###  HERE IT PUTS ENEMIES INTO LISTS ACCORDING TO HOW MANY TIMES 
						##### IT GOT HIT
						if badguy.hit1 == False:
		# 					badguy.vis[0].setFill("green")       	#TESTING
		# 					badguy.vis[0].setOutline("green")		#TESTING
							badguy.hit1 = True
							hit1enemies.append(badguy)
				
						elif badguy.hit2 == False and badguy.hit1 == True:
		# 					badguy.vis[0].setFill("red")
		# 					badguy.vis[0].setOutline("red")
							badguy.hit2 = True
							hit2enemies.append(badguy)
					
						else:
		# 					badguy.hit1 = False
		# 					badguy.hit2 = False
							deadenemies.append(badguy)
							score += 1
							if score % 11 == 10:
								minibattle = False
							scorefunc(win, score)
							if random.random() < 0.08:
								invincible = True
								invincibletext = gr.Text( gr.Point( 250, 400 ), "INVINCIBLE TIME!" )
								invincibletext.setTextColor('white')
								invincibletext.setSize(36)
								invincibletext.draw(win)
							elif random.random() < 0.08:
								bigshots = True
								bigshottext = gr.Text( gr.Point( 250, 500 ), "BIGGER SHOTS!" )
								bigshottext.setTextColor('white')
								bigshottext.setSize(36)
								bigshottext.draw(win)								
					

				##### CHANGES COLORS OF THE ENEMY ACCRODING TO WHICH LIST THEY ARE IN
				for element in hit1enemies:
						element.vis[0].setFill("green")
						element.vis[0].setOutline("green")
				
				for alien in hit2enemies:
						alien.vis[0].setFill("red")
						alien.vis[0].setOutline("red")

				
				for alien1 in deadenemies:
						alien1.undraw()
						os.system("afplay " + "./music/Invaderkilled.wav" + "&")
						enemies.remove(alien1)
	
		
				## SHIP AND ENEMYBALL
				for enball in enemyballList:				
					if collision.collision(enball, ship, dt):
				
						enball.undraw()
						enemyballList.remove( enball )
						if invincible == False:
							health -= 1
						else:
							pass
						healthfunc(win, health)
				
				
				deadenemies = []
				
				#### undraw the ball when it gets out of bounds
				if enemyball.getPosition()[1] < 0:
					enemyball.undraw()
				else:
					newenemyballs.append( enemyball )
				
				##### UPDATES THE WINDOW EVERY 10 LOOPS 
				if frame % 10 == 0:
					win.update()
				
				#### MAKES IT SO THAT ONLY THE BALLS THAT ARE DRAWN ARE UPDATED FOR COLLISION
				#### IN THE NEXT LOOP
				ballList = newballs
				enemyballList = newenemyballs
		
				# GAME OVER 
				if health <= 0:
					os.system("killall afplay ./music/bgm.mp3")
					os.system("afplay ./music/explosion.wav &")
					os.system("afplay ./music/gameover.mov &")
					ship.undraw()
					state = 2
			
				# user input to quit
				if key == 'q':
					state = 3

				frame += 1	

##########################################################################################
				# BOSS BATTLE 
				# BASICALLY THE SAME AS THE CODE ABOVE BUT THE SPAWNING AND THE 
				# REQUIREMENT FOR THE BOSS TO UNDRAW IS DIFFERENT 
				# THE BOSS USES A HP SYSTEM
##########################################################################################

				leveldrawn = False
				while state == 1 and minibattle == False:
					if leveldrawn == False:
						os.system("afplay " + "./music/levelup.mov" + "&")
						lv2 = gr.Text( gr.Point( 250, 100 ), "LEVEL " + str(LEVEL) + " BOSS BATTLE")
						lv2.setTextColor('white')
						lv2.setSize(36)
						instructions = gr.Text( gr.Point(250, 700), "Press Space to Continue")
						instructions.setTextColor('white')
						instructions.draw(win)
						lv2.draw(win)
						leveldrawn = True
					else:
						pass
					key = win.checkKey()
					if key == 'space':
						lv2.setTextColor('black')
						instructions.setTextColor('black')
						start = True
					if key == 'q':
						state = 3
					
					if start == True and minibattle == False:
						while state == 1 and minibattle == False:
							key = win.checkKey()
				
							
							ship.update(dt)
							for i in ballList:
								i.update(dt)
							for j in newenemyballs:
								j.update(dt)
							for k in enemies:
								k.update(dt)
							for l in stars:
								l.update(dt)
				
							if invincible:
								invincibletimer += 1
								if invincibletimer > 200:
									invincible = False
									invincibletimer =0
									invincibletext.setTextColor('black')
						
				
							if invincible == True:
								if shipflash == False:
									ship.undraw()
									shipflash = True
								else:
									ship.draw()
									shipflash = False
						
							if bigshots:
								bigshottimer += 1
								if bigshottimer > 200:
									bigshots = False
									bigshottimer =0
									bigshottext.setTextColor('black')
				
							if bossbattle:
								for everyone in enemies[0:]:
									everyone.undraw()
									enemies.remove(everyone)
						
					
				
							# move ship with user input
							if key == 'Left':
								ship.setVelocity( [-90, 0 ] )
								ship.setFlickerOn()
			
							if key == 'Right':
								ship.setVelocity( [90, 0 ] )	
								ship.setFlickerOn()
					
							# ship boundaries
							if ship.getPosition()[0] > 50:
								ship.setVelocity( [-30, 0] )
							if ship.getPosition()[0] < 0:
								ship.setVelocity( [30, 0] )
	
							# shoot balls from the ship
							if key == 'space':
								if ball.undrawn == True:	
									if bigshots == False:
										ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 2, 2, 'yellow')
									else:
										ball = pho.Ball(win, ship.getPosition()[0], ship.getPosition()[1] + 3, 5, 5, 'yellow')
									ballList.append( ball )
									ball.setVelocity( [1,60])
									ball.draw()
									os.system("afplay " + "./music/shoot.wav" + "&")
								else:
									pass
							# undraw the ball when it gets out of bounds
							if ball.getPosition()[1] > 70:
								ball.undraw()
								newballs.append( ball )
							else:
								newballs.append( ball )

			
							#solve lagging 
							if lagcheck == True:
								time3 = int(time.time())
							else:
								time4 = int(time.time())
							if (time4 - time3) % 40 == 39:
								dt += 0.01
								lagcheck = True
							else:
								lagcheck = False
				
							# regulating number of enemies
							if len(enemies) > 8:
								toomany = True
							else:
								toomany = False
		
							# the actual spawning part
							if toomany == True:
								pass
							else:
								
								if bossbattle == True:							
									boss = pho.Ship(win, 5, 5, 10, 10, angle = 270., dangle = 270., hit1 = False, healthcounter = 50*LEVEL)
									enemies.append( boss )
									boss.draw()
									boss.setPosition( [random.randrange(20, 45, 1), random.randrange(20, 55, 1 )])
									boss.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])])
									bosshp = gr.Text( gr.Point( 250, 100 ), "BOSS HP: " + str(boss.healthcounter))
									bosshp.setSize(36)
									bosshp.setTextColor('white')
									bosshp.draw(win)
									bossbattle = False
									spawn = False
										
				
	
			
						#ENEMY MOVEMENT CONTROL
							for badguy in enemies:
								if badguy.getPosition()[0] > 50:
									badguy.setVelocity( [random.randrange(-60, -40, 1), random.randrange(-30, 30, 10 )] )
								if badguy.getPosition()[0] < 0:
									badguy.setVelocity( [random.randrange(40, 60, 1), random.randrange(-30, 30, 10 )] )	
								if badguy.getPosition()[1] > 65:
									badguy.setVelocity( [random.randrange(-30, 30, 10), random.randrange(-60, -40, 1 )] )
								if badguy.getPosition()[1] < 20:
									badguy.setVelocity( [random.randrange(-30, 30, 1), random.randrange(40, 60, 1 )] )
								if random.random() < 0.05:
									badguy.setVelocity( [random.choice([-80, -70, -60, -50, 50, 60, 70, 80]), random.choice([-80, -70, -60, -50, 50, 60, 70, 80])] )
						# ENEMY SHOOTING BALL
								if random.random() < 0.1:
									enemyball = pho.Ball(win, badguy.getPosition()[0], badguy.getPosition()[1] - 4, 2, 2, 'red')
									enemyballList.append( enemyball )
									enemyball.setVelocity( [0,-70])
									enemyball.draw()

		
			
							# COLLISIONS AND UNDRAWING
							## ENEMY AND SHIP BALL
								if collision.collision( ball, badguy, dt):
									badguy.healthcounter -= 1
									bosshp.setTextColor('black')
									bosshp = gr.Text( gr.Point( 250, 100 ), "BOSS HP: " + str(boss.healthcounter))
									bosshp.setSize(36)
									bosshp.setTextColor('white')
									bosshp.draw(win)
									
									
									ball.undraw()
									ballList.remove(ball)
									bosscolor = random.choice(colors)
									boss.vis[0].setFill(bosscolor)
									boss.vis[0].setOutline(bosscolor)
									if boss.healthcounter <= 0:
										bosshp.setTextColor('black')
										deadenemies.append(badguy)
										score += 100
										scorefunc(win, score)
										minibattle = True
										start = False
										bossbattle = True
										os.system("afplay " + "./music/BossExplode.mp3" + "&")
										LEVEL += 1
										if random.random() < 0.08:
											invincible = True
											invincibletext = gr.Text( gr.Point( 250, 400 ), "INVINCIBLE TIME!" )
											invincibletext.setTextColor('white')
											invincibletext.setSize(36)
											invincibletext.draw(win)
										elif random.random() < 0.08:
											bigshots = True
											bigshottext = gr.Text( gr.Point( 250, 500 ), "BIGGER SHOTS!" )
											bigshottext.setTextColor('white')
											bigshottext.setSize(36)
											bigshottext.draw(win)								
									

		
							for element in hit1enemies:
									element.vis[0].setFill("green")
									element.vis[0].setOutline("green")
				
							for alien in hit2enemies:
									alien.vis[0].setFill("red")
									alien.vis[0].setOutline("red")
									
							for alien1 in deadenemies:
									alien1.undraw()
									os.system("afplay " + "./music/Invaderkilled.wav" + "&")
									enemies.remove(alien1)
	
		
							## SHIP AND ENEMYBALL
							for enball in enemyballList:				
								if collision.collision(enball, ship, dt):
									enball.undraw()
									enemyballList.remove( enball )
									if invincible == False:
										health -= 1
									else:
										pass
									healthfunc(win, health)
				

							deadenemies = []
							# undraw the ball when it gets out of bounds
							if enemyball.getPosition()[1] < 0:
								enemyball.undraw()
							else:
								newenemyballs.append( enemyball )
			
							if frame % 10 == 0:
								win.update()
		
							ballList = newballs
							enemyballList = newenemyballs
		
							# GAME OVER 
							if health <= 0:
								os.system("killall afplay ./music/bgm.mp3")
								os.system("afplay ./music/explosion.wav &")
								os.system("afplay ./music/gameover.mov &")
								ship.undraw()
								state = 2
			
							# user input to quit
							if key == 'q':
								state = 3

		
							frame += 1	



##########################################################################################
#					GAME OVER SCREEN 
#					user can decide to replay the game or quit
##########################################################################################
		drawn = False
		while state == 2:
			if drawn == False:
				
				
				visualship = pho.RotShip(win, 25, 50)
				visualship.draw()
		
				wordplace3 = gr.Point( 250, 200 )
				words3 = "GAME OVER"
				endingwords1 = gr.Text(wordplace3, words3)
				endingwords1.setSize(36)
				endingwords1.setTextColor('white')
				endingwords1.draw(win)
		
				wordplace4 = gr.Point( 250, 700 )
				words4 = "Press S to Play Again!"
				endingwords2 = gr.Text(wordplace4, words4)
				endingwords2.setSize(36)
				endingwords2.setTextColor('white')
				endingwords2.draw(win)
				
				endingwords3 = gr.Text(gr.Point( 250, 600) , "Score: " + str(score))
				endingwords3.setSize(36)
				endingwords3.setTextColor('white')
				endingwords3.draw(win)
				
				drawn = True
				
			else:		
				pass
		
			visualship.update(dt)
			
			key = win.checkKey()
			if key == 's':
				startingwords1.undraw()
				startingwords2.undraw()
				state = 1
			
			if key == 'q':
				state = 3

##########################################################################################
#				STATE 3: LED TO HERE WHEN USER DECIDES TO QUIT WHEN IN ANY OF THE OTHER SCREENS
#				KILLS THE MUSIC 
##########################################################################################
		if state == 3:
			os.system("killall afplay ./music/bgm.mp3")
			win.close()
			break
Пример #6
0
def main():
    win = gr.GraphWin('Space Game', 500, 500, False)
    blocks = [pho.RotatingBlock(win, 10, 20, 5, 5),pho.RotatingBlock(win, 25, 20, 5, 5),pho.RotatingBlock(win, 40, 20, 5, 5),
    pho.RotatingBlock(win, 25, 36, 3, 11), pho.RotatingBlock(win, 25, 36, 11, 3)]
    b = gr.Image(gr.Point(250,250),"background.gif")
    b.draw(win)
    start = gr.Text(gr.Point(250, 250), "Start")
    start.draw(win)
    obstacles = pho.buildGame(win, 50, 50, 50, 4)
    ball = pho.Ball(win, 25, 25)
    pho.launch(ball, 40, 10, 10, 10, 200)
    ball.setVelocity([0, 100])
    ball.setForce([0, -50])
    ball.setElasticity(0.9)
    ball.draw()
    
    for block in blocks:
        block.setRotVelocity(300)
        block.draw()
        
    dt = 0.01
    frame = 0
    
    win.getMouse()
    
    while win.checkMouse() == None:
        collided = False
        for item in obstacles:
            if col.collision(ball, item, dt) == True:
                collided = True
                ball.setFill(gr.color_rgb(random.randint(1,255),random.randint(1,255),random.randint(1,255)))
        for block in blocks:
            if col.collision(ball, block, dt) == True:
                collided = True
                ball.setFill(gr.color_rgb(random.randint(1,255),random.randint(1,255),random.randint(1,255)))            
        if collided == False:
            ball.update(dt)
                    
        for block in blocks:
            block.update(dt)
            block.setFill('grey')
            block.setOutline('grey')
        
        movingBlockDown = obstacles[-1]
        movingBlockUp = obstacles[-2]
        
        n = win.checkKey()
         
        if n == "Right":   
            movingBlockDown.moveBlock(20,0)
            movingBlockDown.update(dt)
            
        if n == "Left":
            movingBlockDown.moveBlock(-20, 0)
            movingBlockDown.update(dt)
            
        if n == "d":   
            movingBlockUp.moveBlock(20,0)
            movingBlockUp.update(dt)
            
        if n == "a":
            movingBlockUp.moveBlock(-20, 0)
            movingBlockUp.update(dt)
            
        if n == "space":
            pho.launch(ball, 10, 10, 20, 20, 100)
            
        if (ball.getPosition()[0] < 0 or ball.getPosition()[0] > win.getWidth()) or (ball.getPosition()[1] < 0 or ball.getPosition()[1] > win.getHeight()):
            ball.setPosition([25, 25])
            ball.setVelocity([0, random.randint(-10, 10)])
            #relaunch the ball
            pho.launch(ball, 10, 10, 20, 20, 100)
            
        if frame % 10 == 0:
            win.update()
                
        frame += 1
            
    win.getMouse()
    win.close()
Пример #7
0
def main():
    """ Main loop """

    win = gr.GraphWin("Asteroids", 700, 700, False)
    win.setBackground("black")

    # Intro texts
    welcomeText = gr.Text(gr.Point(350, 310), "Welcome to Asteroids!")
    welcomeText.setSize(30)
    welcomeText.setTextColor("white")
    welcomeText.draw(win)

    welcomeText2 = gr.Text(gr.Point(350, 400), "Press space to start")
    welcomeText2.setSize(20)
    welcomeText2.setTextColor("white")
    welcomeText2.draw(win)

    controlsText1 = gr.Text(
        gr.Point(350, 350),
        "Use up, right, and left arrow keys to move. Press space to use your boost."
    )
    controlsText1.setSize(20)
    controlsText1.setTextColor("white")
    controlsText1.draw(win)

    key = ""
    frame = 0

    # Flickering effect
    while key != "space":
        key = win.checkKey()
        if key != "space" and frame % 3000 == 100:
            welcomeText2.undraw()
        elif frame % 3000 == 1000:
            welcomeText2.draw(win)
        frame += 1

    welcomeText2.undraw()
    welcomeText.undraw()
    controlsText1.undraw()

    # Lives text
    livesText = gr.Text(gr.Point(50, 30), "Lives: ")
    livesText.setTextColor("white")
    livesText.draw(win)

    # Boost text
    boostText = gr.Text(gr.Point(550, 30), "Boost: ")
    boostText.setTextColor("white")
    boostText.draw(win)

    # Boost bar
    boostBar = pho.Bar(win, 58, 66, 10, 2)
    boostBar.setColor("blue")
    boostBar.draw()

    # Boost bar's outline
    boostBarOutline = pho.Bar(win, 57.9, 65.9, 10.2, 2.25)
    boostBarOutline.setOutline("white")
    boostBarOutline.draw()

    # Creating the spaceship
    spaceship = ship.Ship(win, 35, 35)
    spaceship.draw()

    # Creating the lives
    livesLeft = lifeCreator(3, win)

    # Variables for the game:

    asteroids = []  # List of asteroids
    explosions = []  # List for explosion animation
    frame = 0  # Frame number
    key = ""  # Current pressed key
    dt = 0.01  # Update time
    delta = 3  # Thrust rate
    gamma = 60  # Turn rate
    zeta = 8  # Boost rate
    respawnFrame = -1000  # When to respawn the ship (initially set to small number)
    expRad = 60  # Explosion radius variable
    boostRemaining = 100  # Remaining boost
    gameOver = False  # If the player dies enough times, we call closing scene
    score = 0  # Player's score

    while key != "q":

        key = win.checkKey()
        collided = False

        # spawn asteroids
        asteroid = asteroidSpawner(frame, 120, win)

        # left turn
        if key == "Left":
            spaceship.setRotVelocity(spaceship.getRotVelocity() + gamma)
            spaceship.setFlickerColor(["yellow", "orange"])
            spaceship.setFlickerOn()

        # right turn
        elif key == "Right":
            spaceship.setRotVelocity(spaceship.getRotVelocity() - gamma)
            spaceship.setFlickerColor(["yellow", "orange"])
            spaceship.setFlickerOn()

        # thrust
        elif key == "Up":
            a = spaceship.getAngle()
            theta = a * math.pi / 180
            v = spaceship.getVelocity()

            v_new_x = v[0] + math.cos(theta) * delta
            v_new_y = v[1] + math.sin(theta) * delta

            spaceship.setVelocity([v_new_x, v_new_y])

            spaceship.setFlickerColor(["yellow", "orange"])
            spaceship.setFlickerOn()

        # boost (if there is boost and the ship is not dead)
        elif key == "space" and boostRemaining > 10 and respawnFrame < 0:
            a = spaceship.getAngle()
            theta = a * math.pi / 180
            v = spaceship.getVelocity()

            v_new_x = v[0] + math.cos(theta) * zeta
            v_new_y = v[1] + math.sin(theta) * zeta

            spaceship.setVelocity([v_new_x, v_new_y])

            spaceship.setFlickerColor(["light blue", "dark blue"])
            spaceship.setFlickerOn()
            boostRemaining -= 10

        # if we have less than 100 boost, we update the bar
        # and then increment the remaining boost (if the ship is alive)
        if boostRemaining < 100 and respawnFrame < 0:
            boostBar.setWidth((boostRemaining / 100) * 10)
            boostBar.update()
            boostRemaining += 0.1

        # if we are not pressing any key, decrease the rotational velocity
        if key == "":
            if spaceship.getRotVelocity() != 0:
                spaceship.setRotVelocity(spaceship.getRotVelocity() * 0.99)

        # if we create an asteroid, append it to the list
        if asteroid != None:
            asteroids.append(asteroid)

        # update asteroids and set their color to white
        for asteroid in asteroids:
            asteroid.update(dt)
            asteroid.setOutline("white")
            asteroid.setFill("black")

        # update the spaceship
        spaceship.update(dt)

        # erase out-of-bounds asteroids every 120 frames
        # also increment score by 100 for each deleted asteroid
        if frame % 120 == 0:
            numAsteroids = len(asteroids)
            asteroids = asteroidEraser(asteroids)
            newNumAsteroids = len(asteroids)
            score += 100 * (numAsteroids - newNumAsteroids)

        # getting the corners of the spaceship
        spaceshipCorners = spaceship.getBodyPoints()

        # checking for collisions
        for asteroid in asteroids:
            astCenter = asteroid.getAnchor()
            shipCenter = spaceship.getPosition()
            dx = (astCenter[0] - shipCenter[0])**2
            dy = (astCenter[1] - shipCenter[1])**2
            # if the centers are close enough, we can check for collisions
            if dx + dy < 400:
                astPts = asteroid.getCorners()
                collision = collisionDetecter(spaceshipCorners, astPts)
                if collision == True:
                    collided = True
                    score += frame

        # if there is a collision
        if collided == True:
            respawnFrame = frame
            dyingPoint = spaceship.getPosition()
            spaceship.undraw()
            # we set body points to somewhere distant so we don't get extra collisions
            spaceship.setBodyPoints([[1000, 1000], [1000, 1000], [1000, 1000]])
            expRad = 0

        # if explosion happens
        if expRad < 60:

            # vary the color of the explosion between 2 colors
            if expRad % 2 == 0:
                explosion = pho.Ball(win, dyingPoint[0], dyingPoint[1],
                                     expRad / 10)
                explosion.setColor("dark red")
                explosion.draw()
                explosions.append(explosion)
            else:
                explosion = pho.Ball(win, dyingPoint[0], dyingPoint[1],
                                     expRad / 10)
                explosion.setColor("orange")
                explosion.draw()
                explosions.append(explosion)
            # increase the radius
            expRad += 1

            if expRad == 60:  # when we reach full size, delete the explosions
                for explosion in explosions:
                    explosion.undraw()

        if frame == respawnFrame + 90:  # 90 frames after death:

            asteroids, livesLeft = respawn(win, livesLeft, asteroids,
                                           spaceship)

            if len(livesLeft) == 0:  # if the player is out of lives

                key = win.checkKey()

                # Undraw all the elements
                spaceship.undraw()
                livesText.undraw()
                boostBar.undraw()
                boostBarOutline.undraw()
                boostText.undraw()

                # Print ending texts
                endingText = gr.Text(gr.Point(350, 290), "Game over...")
                endingText.setSize(30)
                endingText.setTextColor("white")
                endingText.draw(win)

                finalScore = gr.Text(gr.Point(350, 330),
                                     "Your score: " + str(score // 10))
                finalScore.setSize(18)
                finalScore.setTextColor("white")
                finalScore.draw(win)

                instructions1 = gr.Text(gr.Point(350, 360),
                                        "Press p to play again")
                instructions1.setSize(18)
                instructions1.setTextColor("white")
                instructions1.draw(win)

                instructions2 = gr.Text(gr.Point(350, 390), "Press q to quit")
                instructions2.setSize(18)
                instructions2.setTextColor("white")
                instructions2.draw(win)

                # Check for response
                while key != "p":

                    key = win.checkKey()

                    if key == "q":
                        break

                if key == "p":  # draw everything back, set everything back

                    # draw the necessary items
                    spaceship.draw()
                    livesText.draw(win)
                    boostBar.draw()
                    boostBarOutline.draw()
                    boostText.draw(win)

                    # undraw ending texts
                    endingText.undraw()
                    instructions1.undraw()
                    instructions2.undraw()
                    finalScore.undraw()

                    # set the variables
                    boostRemaining = 100
                    boostBar.setWidth(10)
                    boostBar.update()
                    livesLeft = lifeCreator(3, win)  # giving player 3 lives
                    respawnFrame = -1000  # setting it to something small
                    frame = 0  # resetting the frame
                    score = 0  # resetting the score
                    continue

                if key == "q":  # quit the game
                    break

            # set the respawn frame to something very small
            respawnFrame = -1000

            # reset the frame count
            frame = 0

            # reset the remaining boost and the boostbar
            boostRemaining = 100
            boostBar.setWidth((boostRemaining / 100) * 10)
            boostBar.update()

        # mechanism for making the ship stay inside screen
        moveit = False
        p = spaceship.getPosition()

        if p[0] < 0:
            p[0] += win.getWidth() / 10
            moveit = True
        elif p[0] > win.getWidth() / 10:
            p[0] -= win.getWidth() / 10
            moveit = True

        if p[1] < 0:
            p[1] += win.getHeight() / 10
            moveit = True
        elif p[1] > win.getHeight() / 10:
            p[1] -= win.getHeight() / 10
            moveit = True

        if moveit:
            spaceship.setPosition(p)
            moveit = False

        if frame % 10 == 0:
            win.update()
            time.sleep(dt * 0.5)

        frame += 1

    win.close()
Пример #8
0
def buildGame(win, x0, y0, height, width):

    # obstacles: floors, left, right, blocks
    awkwardBLock = pho.Block(win,
                             x0 + 40,
                             y0 + 14,
                             height + 3,
                             width + 10,
                             coloring='brown')
    floor_left = pho.Block(win,
                           x0 + 0,
                           y0 + 10,
                           height + 35,
                           width + 3,
                           coloring='green')
    floor_right = pho.Block(win,
                            x0 + 40,
                            y0 + 10,
                            height + 20,
                            width + 3,
                            coloring='green')
    left = pho.Wall(win,
                    x0 + 2,
                    y0 + 10,
                    height + 70,
                    width + 3,
                    coloring='DarkBlue')
    right = pho.Wall(win,
                     x0 + 48,
                     y0 + 10,
                     height + 70,
                     width + 3,
                     coloring='DarkBlue')
    block1 = pho.Block(win,
                       x0 + 15,
                       y0 + 25,
                       height + 3,
                       width + 3,
                       coloring='brown')
    block2 = pho.Block(win,
                       x0 + 35,
                       y0 + 25,
                       height + 3,
                       width + 3,
                       coloring='brown')
    block3 = pho.Block(win,
                       x0 + 25,
                       y0 + 25,
                       height + 3,
                       width + 3,
                       coloring='brown')
    top_left = pho.Block(win,
                         x0 + 0,
                         y0 + 58,
                         height + 35,
                         width + 3,
                         coloring='brown')
    top_right = pho.Block(win,
                          x0 + 40,
                          y0 + 58,
                          height + 20,
                          width + 3,
                          coloring='brown')
    ball3 = pho.Ball(win,
                     x0 + 45,
                     y0 + 56,
                     radius=3,
                     coloring='DarkGoldenrod4')
    ball4 = pho.Ball(win,
                     x0 + 5,
                     y0 + 55,
                     radius=3.3,
                     coloring='DarkGoldenrod4')
    obstacles = [
        ball3, ball4, floor_right, block2, floor_left, top_right, top_left,
        block1, block3, right, left, awkwardBLock
    ]
    for obstacle in obstacles:
        obstacle.draw()
        obstacle.setElasticity(1.01)
    return obstacles
Пример #9
0
def main():
    # create a GraphWin
    win = gr.GraphWin("Golf", 500, 600, False)
    win.setBackground('alice blue')
    # Assign to obstacles the result of calling buildGame
    obstacles = buildGame(win, 0, 0, 0, 0)
    #make launchpad
    launchpad = pho.Triangle(win, 41, 11, 5, 5, coloring='orange')
    launchpad.draw()
    # Make a Ball object, draw it
    ball = pho.Ball(win, 43, 9.5)
    ball.draw()

    # make rotating blocks
    block = pho.RotatingBlock(win, 40, 45, 3, 7)
    block1 = pho.RotatingBlock(win, 10, 30, 3, 7)
    block.draw()
    block1.draw()
    # make paddles
    left_paddle = pho.RotatingBlock(win, 19, 8.5, 6.8, 2)
    left_paddle.setAngle(315)
    right_paddle = pho.RotatingBlock(win, 29, 8.5, 6.8, 2)
    right_paddle.setAngle(45)
    paddles = [left_paddle, right_paddle]
    for paddle in paddles:
        paddle.draw()
        obstacles.append(paddle)
    dt = 0.03
    # start after clicking mouse
    win.getMouse()
    # assign to frame the value 0
    frame = 0
    while win.checkMouse() == None:
        block.setRotVelocity(200)
        block.update(dt)
        obstacles.append(block)
        block1.setRotVelocity(200)
        block1.update(dt)
        obstacles.append(block1)
        collided = False
        for item in obstacles:
            # if the result of calling the collision function with the ball and the item is True
            if coll.collision(ball, item, dt) == True:
                collided == True
        if collided == False:
            ball.update(dt)
    # user input to allow interaction
        n = win.checkKey()
        if n == "space":
            print n
            left_paddle.setRotVelocity(400)
            right_paddle.setRotVelocity(-400)
        if left_paddle.angle > 360:
            left_paddle.setAngle(360)
            left_paddle.setRotVelocity(-300)
        if left_paddle.angle < 315:
            left_paddle.setRotVelocity(0)
            left_paddle.setAngle(315)
        if right_paddle.angle < 0:
            right_paddle.setAngle(0)
            right_paddle.setRotVelocity(300)
        if right_paddle.angle > 45:
            right_paddle.setRotVelocity(0)
            right_paddle.setAngle(45)
        left_paddle.update(dt)
        right_paddle.update(dt)
        p = ball.getPosition()
        # if the ball is out of the window, user launches it
        if p[1] < 10 or p[1] > 60 or p[0] < 0 or p[0] > 50:
            if n == "0":
                ball.setVelocity([-3, 5])
                launch(ball, 43, 13, 5, 15, 250)
        if n == "period":
            ball.setVelocity([0, 0])
            ball.setPosition([43, 9])
            ball.update(dt)


# check which key
#		m = win.getKey()
#		print m
        if frame % 10 == 0:
            win.update()
            time.sleep(0.01)
        frame += 1

    # wait for a mouse click, then close the window
    win.getMouse()
    win.close()
Пример #10
0
def main():
    # create a GraphWin
    win = gr.GraphWin("extended course", 500, 600, False)
    win.setBackground('alice blue')
    # Assign to obstacles the result of calling buildGame
    obstacles = buildGame(win, 0, 0, 0, 0)
    # start after clicking mouse
    win.getMouse()
    # Make a Ball object, draw it, and launch it into the scene
    ball = pho.Ball(win, 45, 3)
    ball.draw()
    ball.setVelocity([-3, 5])
    launch(ball, 43, 13, 5, 15, 250)
    # make rotating blocks
    block = pho.RotatingBlock(win, 35, 40, 3, 6, coloring='grey')
    block1 = pho.RotatingBlock(win, 15, 20, 3, 6, coloring='grey')
    block.draw()
    block1.draw()
    # make paddles
    left_paddle = pho.RotatingBlock(win,
                                    19,
                                    8.5,
                                    7,
                                    1.5,
                                    coloring='LemonChiffon')
    left_paddle.setAngle(300)
    right_paddle = pho.RotatingBlock(win,
                                     29,
                                     8.5,
                                     6.8,
                                     1.5,
                                     coloring='LemonChiffon')
    right_paddle.setAngle(60)
    paddles = [left_paddle, right_paddle]
    for paddle in paddles:
        paddle.draw()
        obstacles.append(paddle)
    dt = 0.03
    # assign to frame the value 0
    frame = 0
    while win.checkMouse() == None:
        block.setRotVelocity(200)
        block.update(dt)
        obstacles.append(block)
        block1.setRotVelocity(200)
        block1.update(dt)
        obstacles.append(block1)
        collided = False
        for item in obstacles:
            # if the result of calling the collision function with the ball and the item is True
            if coll.collision(ball, item, dt) == True:
                collided == True
        if collided == False:
            ball.update(dt)
    # user input to allow interaction
        n = win.checkKey()
        if n == "space":
            print n
            left_paddle.setRotVelocity(300)
            right_paddle.setRotVelocity(-300)
        if left_paddle.angle > 360:
            left_paddle.setAngle(360)
            left_paddle.setRotVelocity(-300)
        if left_paddle.angle < 300:
            left_paddle.setRotVelocity(0)
            left_paddle.setAngle(300)
        if right_paddle.angle < 0:
            right_paddle.setAngle(0)
            right_paddle.setRotVelocity(300)
        if right_paddle.angle > 60:
            right_paddle.setRotVelocity(0)
            right_paddle.setAngle(60)
        left_paddle.update(dt)
        right_paddle.update(dt)
        # check which key
        # 		m = win.getKey()
        # 		print m
        if frame % 10 == 0:
            win.update()
            time.sleep(0.001)
        frame += 1
    # wait for a mouse click, then close the window
    win.getMouse()
    win.close()
Пример #11
0
def buildGame(win, x0, y0, height, width):
    # obstacles: floors, left, right, blocks
    awkwardBLock = pho.Block(win,
                             x0 + 40,
                             y0 + 14,
                             height + 3,
                             width + 10,
                             coloring='brown')
    top = pho.Floor(win,
                    x0 + 0,
                    y0 + 58,
                    height + 50,
                    width + 3,
                    coloring='dark green')
    left = pho.Wall(win,
                    x0 + 2,
                    y0 + 10,
                    height + 70,
                    width + 3,
                    coloring='DarkBlue')
    right = pho.Wall(win,
                     x0 + 48,
                     y0 + 10,
                     height + 70,
                     width + 3,
                     coloring='DarkBlue')
    block1 = pho.Block(win,
                       x0 + 10,
                       y0 + 35,
                       height + 3,
                       width + 3,
                       coloring='brown')
    block2 = pho.Block(win,
                       x0 + 40,
                       y0 + 35,
                       height + 3,
                       width + 3,
                       coloring='brown')
    floor_left = pho.Block(win,
                           x0 + 0,
                           y0 + 10,
                           height + 35,
                           width + 3,
                           coloring='brown')
    floor_right = pho.Block(win,
                            x0 + 40,
                            y0 + 10,
                            height + 20,
                            width + 3,
                            coloring='brown')
    samosa = pho.Triangle(win,
                          x0 + 25,
                          y0 + 40,
                          height + 4,
                          width + 4,
                          coloring='orange')
    tri = pho.Triangle(win,
                       x0 + 5,
                       y0 + 50,
                       height + 4,
                       width + 4,
                       coloring='orange')
    samosa1 = pho.Triangle(win,
                           x0 + 23,
                           y0 + 36,
                           height + 4,
                           width + 4,
                           coloring='orange')
    block3 = pho.Block(win,
                       x0 + 25,
                       y0 + 35,
                       height + 5,
                       width + 5,
                       coloring='brown')
    samosa2 = pho.Triangle(win,
                           x0 + 27,
                           y0 + 36,
                           height + 4,
                           width + 4,
                           coloring='orange')
    rathole = pho.Hexagon(win,
                          x0 + 18,
                          y0 + 52,
                          height + 5,
                          width + 5,
                          coloring='hotpink')
    bounce1 = pho.Hexagon(win,
                          x0 + 5,
                          y0 + 40,
                          height + 4,
                          width + 4,
                          coloring='hotpink')
    ball1 = pho.Ball(win, x0 + 5, y0 + 14, radius=3, coloring='DarkGoldenrod4')
    ball3 = pho.Ball(win,
                     x0 + 47,
                     y0 + 56,
                     radius=3,
                     coloring='DarkGoldenrod4')
    ball4 = pho.Ball(win,
                     x0 + 5,
                     y0 + 55,
                     radius=3.3,
                     coloring='DarkGoldenrod4')

    obstacles = [
        ball4, tri, ball3, ball1, rathole, bounce1, samosa2, samosa1, samosa,
        block2, top, floor_right, floor_left, block1, right, left, awkwardBLock
    ]
    for obstacle in obstacles:
        obstacle.draw()
        obstacle.setElasticity(1.01)
    return obstacles
Пример #12
0
def main( argv ):

    # make a window
    win = gr.GraphWin( "Drop", 500, 500, False )

    # init the bricks and boards
    blocks = init_blocks(win.getWidth()/2, 50, 200, 5, win )

    # draw the bricks and boards into the window
    for item in blocks:
        item.draw()

    # create and draw the ball, giving it a downward acceleration
    lefttest = 135
    righttest = 365
    belowtest = 150
    demo = pho.Ball( win, 10, [lefttest, 450], [0, 0], [0, -4], 'black')
    demo.draw()

    txt = gr.Text( gr.Point( 80, 250 ), 'Click to continue' )
    txt.setSize( 12 )
    txt.draw(win)

    win.getMouse()
    txt.setText( 'Testing left' )
    win.update()

    # time step 
    dt = 0.02

    # loop for 1500 time steps
    for i in range(3200):

        # update the ball falling down
        demo.update( dt )

        # keep track of which bricks don't get hit
        newblocks = []
        
        # loop over the blocks
        for block in blocks:
            # if there is a collision
            if coll.collision_ball_block( demo, block, dt, False ):
                # undraw the original block
                block.undraw( )
            else:
                # if no collision, keep the brick 
                newblocks.append(block)
        # update the bricks list
        blocks = newblocks

        # check if the ball has gone out of the window
        pos = demo.getPosition( )
        if pos[1] < 0 or pos[0] > 500:
            if pos[0] == lefttest:
                txt.setText('Testing bottom')
                txt.setFill( 'green')
                demo.setVelocity( [0, 0] )
                demo.setAcceleration( [4, 0] )
                demo.setPosition([-10, belowtest] )
            elif pos[1] == belowtest:
                txt.setText('Testing right')
                txt.setFill( 'blue')
                demo.setVelocity( [0, 0] )
                demo.setAcceleration( [0, -4] )
                demo.setPosition( [righttest, 450] )
            elif pos[0] == righttest:
                txt.setText('Testing hits')
                txt.setFill( 'red')
                demo.setVelocity( [0, 0] )
                demo.setPosition( [250, 450] )

        # periodically update the window
        if i % 10 == 0:
            win.update()

    # wait for a mouse click to close
    txt.setText( 'Click to contnue' )
    txt.move( 10, 0 )
    txt.setFill( 'black' )
    win.update()
    win.getMouse()

    txt.setText( 'See ya' )
    win.update()
    time.sleep(0.2)
    win.close()