H a n d s o n, p r o j e c t b a s e d
Download 4.21 Mb. Pdf ko'rish
|
Python Crash Course, 2nd Edition
Creating a Row of Aliens
We’re ready to generate a full row of aliens. Because our code for making a single alien works, we’ll rewrite _create_fleet() to make a whole row of aliens: def _create_fleet(self): """Create the fleet of aliens.""" # Create an alien and find the number of aliens in a row. # Spacing between each alien is equal to one alien width. u alien = Alien(self) v alien_width = alien.rect.width w available_space_x = self.settings.screen_width - (2 * alien_width) number_aliens_x = available_space_x // (2 * alien_width) # Create the first row of aliens. x for alien_number in range(number_aliens_x): # Create an alien and place it in the row. alien = Alien(self) y alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x self.aliens.add(alien) alien_invasion.py Aliens! 261 We’ve already thought through most of this code. We need to know the alien’s width and height to place aliens, so we create an alien at u before we perform calculations. This alien won’t be part of the fleet, so don’t add it to the group aliens . At v we get the alien’s width from its rect attribute and store this value in alien_width so we don’t have to keep working through the rect attribute. At w we calculate the horizontal space available for aliens and the number of aliens that can fit into that space. Next, we set up a loop that counts from 0 to the number of aliens we need to make x. In the main body of the loop, we create a new alien and then set its x-coordinate value to place it in the row y. Each alien is pushed to the right one alien width from the left margin. Next, we multiply the alien width by 2 to account for the space each alien takes up, including the empty space to its right, and we multiply this amount by the alien’s position in the row. We use the alien’s x attribute to set the position of its rect. Then we add each new alien to the group aliens . When you run Alien Invasion now, you should see the first row of aliens appear, as in Figure 13-3. Figure 13-3: The first row of aliens The first row is offset to the left, which is actually good for gameplay. The reason is that we want the fleet to move right until it hits the edge of the screen, then drop down a bit, then move left, and so forth. Like the classic game Space Invaders, this movement is more interesting than having the fleet drop straight down. We’ll continue this motion until all aliens are shot down or until an alien hits the ship or the bottom of the screen. |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling