2015/11/6 writing games with Python, Pygame primer (6): Control a large number of objects

Source: Internet
Author: User

Yesterday we have implemented three basic classes of this game.

But now it is still not able to make a suitable game, after all, only one enemy game is very boring. So we need a lot of bullets and a lot of enemy aircraft.

So, we're going to create a list, which holds an instance of bullet or enemy.

Take bullet as an example:

# Create Bullets  for  in range (6):    bullet.append (Bullet ()) ...  for  in bullet:# Move Bullets         b.move (time_passed_second) ...  for  in bullet:# Show Bullets        screen.blit (B.image, (b.x, B.Y))

We can use this code to replace the part where we originally created the bullets, moved the bullets and displayed the bullets. But the actual running result has not changed. Why is this?

Because a list of bullets are created and launched in the same way, all bullets are fired at the same time, reaching the top of the screen, and then firing simultaneously. There is no difference between this effect and the firing of a shot. So we're going to have to launch it by a certain interval.

In addition, if you go back to the top of the screen, re-fired bullets and on time fired bullets mixed together, disrupting the launch rhythm, so the method of bullet recycling also need to change. We can choose to send each bullet only to write its launch, do not write its recycling, but so each fired a shot will create a space, read a picture, this will consume memory resources, generally should be avoided.

Then we have to solve two problems, one is timed launch, and the other is recycling bullets.

Python has a dedicated time module, but, in the game, we have a fixed frame rate of the loop, as long as a counter to count, every number of cycles to start once, you can achieve the timing effect.

For example, we define a bullet firing interval interval_bullet, let it increment or decrement, after reaching a certain number, reset the interval, and run a specific program, you can make the bullet timed launch.

If we want to reuse a bullet, we can let the bullet itself have a property to indicate whether the bullet should be activated, and only if it is active, we will handle its movement and display.

The bullets themselves can be reused, and we use a circular queue structure to handle the use of bullets.

According to this method, we can modify the Bullet class:

classBullet (object):def __init__(self): self.x=0 Self.y=-100Self.speed= 600Self.image=pygame.image.load (bullet_image_filename). Convert_alpha () self.active=FalsedefMove (self, passed_time_second):ifSelf.y <0:self.active=FalseElse: Self.y-= self.speed*Passed_time_seconddefRestart (self): self.active=True MouseX, Mousey=Pygame.mouse.get_pos () self.x= Mousex-self.image.get_width ()/2Self.y= Mousey-self.image.get_width ()/2

Added a method to reactivate the bullet restart (), and added a data property active to mark whether the bullet itself was activated. We then change the code to add bullets, move bullets, and show bullet parts to this:

Bullet = [] forIinchRange (6):#total number of bulletsbullet.append (Bullet ()) Interval_bullet= 25#number of frames fired bulletsIndex_bullet = 0#Initialize bullet coordinates. .. interval_bullet-= 1ifInterval_bullet <=0:interval_bullet= 25Bullet[index_bullet].restart () Index_bullet= (index_bullet + 1)% 6 forBinchBullet:ifB.active:b.move (Time_passed_second)#Moving BulletsScreen.blit (B.image, (b.x, B.Y))#Show Bullets

The result is this:

Will the plane be far behind when the bullet is finished?

We can think of their own how to write the enemy aircraft, the enemy is different, before and after the interval should have more randomness.

I do not give a step-by-step guide here, the implementation of their own code to paste up, perhaps we have a better control, you can exchange a bit:

#-*-Coding:utf8-*-Background_image_filename='Background.png'Mouse_image_filename='Hero.png'Bullet_image_filename='Bullet.png'Enemy_image_filename='Enemy.png'#Specify the image file name ImportPygame#Import Pygame Library fromSysImportExit#borrow an exit function from the SYS module to exit the program fromRandomImportRandint#Introducing Random numbers#define a bullet class that encapsulates the data and methods of a bulletclassBullet (object):def __init__(self): self.x=0 Self.y=-100Self.speed= 600Self.image=pygame.image.load (bullet_image_filename). Convert_alpha () self.active=FalsedefMove (self, passed_time_second):ifSelf.y <0:self.active=FalseElse: Self.y-= self.speed*Passed_time_seconddefRestart (self): self.active=True MouseX, Mousey=Pygame.mouse.get_pos () self.x= Mousex-self.image.get_width ()/2Self.y= Mousey-self.image.get_width ()/2classEnemy (object):#define a enemy class that encapsulates the data and methods of the enemy aircraft    defRestart (self): self.x= Randint (-30,400) Self.y= Randint (-100,-50) Self.speed= Randint (100,400) self.active=Truedef __init__(self): Self.restart () self.active=False self.image=pygame.image.load (enemy_image_filename). Convert_alpha ()defMove (self, passed_time_second):ifSELF.Y < 650: Self.y+ = self.speed*Passed_time_secondElse: Self.active=Falsepygame.init ()#Initialize Pygame, prepare for hardware useScreen = Pygame.display.set_mode ((480, 650), 0, 32)#A window was createdPygame.display.set_caption ("planefight!")#Set Window captionpygame.mouse.set_visible (False) Background=pygame.image.load (Background_image_filename). CONVERT () mouse_cursor=pygame.image.load (mouse_image_filename). Convert_alpha ()#loading and converting imagesBullet = [] forIinchRange (6):#total number of bulletsbullet.append (Bullet ()) Interval_bullet= 25#number of frames fired bulletsIndex_bullet = 0#Initialize bullet coordinatesEnemy = [] forIinchRange (10):#total number of enemy aircraftEnemy.append (Enemy ()) Interval_enemy= 100#the interval at which the enemy aircraft appearedIndex_enemy = 0#Initialize the coordinates of the enemy aircraftClock =Pygame.time.Clock () whileTrue:#Game main Loop      forEventinchpygame.event.get ():ifEvent.type = =Pygame. QUIT:#exit the program after receiving the exit eventPygame.quit () exit () time_passed= Clock.tick (100) Time_passed_second= time_passed/1000.0Screen.blit (background, (0,0))#put the background picture upX, y =Pygame.mouse.get_pos ()#Get mouse positionInterval_bullet-= 1ifInterval_bullet <=0:interval_bullet= 25Bullet[index_bullet].restart ()#Reset BulletsIndex_bullet = (index_bullet + 1)% 6#Loop Increment             forBinchBullet:ifB.active:b.move (Time_passed_second)#Moving BulletsScreen.blit (B.image, (b.x, B.Y))#Show BulletsInterval_enemy-= 1ifInterval_enemy <=0:interval_enemy= Randint (30,100) Enemy[index_enemy].restart ()#Reset AircraftIndex_enemy = (index_enemy + 1)% 10#Loop Increment     forEinchEnemy:ifE.active:e.move (Time_passed_second)#Moving enemy aircraftScreen.blit (E.image, (e.x, e.y))#Show enemy aircraftx-= Mouse_cursor.get_width ()/2y-= Mouse_cursor.get_height ()/2#calculates the position of the upper-left corner of the cursor     #Screen.blit (Bullet.image, (Bullet.x, bullet.y))Screen.blit (Mouse_cursor, (x, y))#draw all the elements up .pygame.display.update ()#Refresh the screen .

2015/11/6 writing games with Python, Pygame primer (6): Control a large number of objects

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.