外星人checkingmedia解决:外星人入侵游戏中的外星人不动

我正在尝试学习 python,现在正在进行外星人入侵游戏。我在使外星人向右移动的地方,由于某种原因,外星人舰队不会移动。每当我让它移动时,要么只有边缘在与外星人一起移动,要么整个舰队以奇怪的方式移动(附图image1

image2

alien_invasion.py

```
import sys
import pygame
from settings import settings
from ship import Ship
from bullets import Bullet
from alien import Alien
class AlienInvasion:
"""overall class to manage game assets and behaviours"""
def __init__(self):
    """initialise game and create game resources"""
    pygame.init()
    self.settings=settings()
    self.screen=pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    self.ship=Ship(self)
    self.bullets=pygame.sprite.Group()
    self.aliens=pygame.sprite.Group()
def run_game(self):
    """start main loop for the game"""
    while True:
        self._check_events()
        self.ship.update()
        self._update_bullets()
        self._create_fleet()
        self._update_screen()
        self._update_aliens()   
def _check_events(self):
    #watch for keyboard and mouse events.
    for event in pygame.event.get():
        if event.type==pygame.QUIT:
            sys.exit()
        
        elif event.type==pygame.KEYDOWN:
            self._check_KEYDOWN_events(event)
            
        elif event.type==pygame.KEYUP:
            self._check_KEYUP_events(event)
                        
        
def _check_KEYDOWN_events(self,event):
    """respond to keypresses."""
    if event.key==pygame.K_RIGHT:
        self.ship.moving_right=True
    elif event.key==pygame.K_LEFT:
        self.ship.moving_left=True
    elif event.key==pygame.K_SPACE:
        self._fire_bullet()
    elif event.key==pygame.K_q:
        sys.exit()
    elif event.key==pygame.K_f:
        self.screen=pygame.display.set_mode((0,0),pygame.FULLSCREEN)
        self.settings.screen_width=self.screen.get_rect().width
        self.settings.screen_height=self.screen.get_rect().height
def _check_KEYUP_events(self,event):
    """respond to key releases."""
    if event.key==pygame.K_RIGHT:
        self.ship.moving_right=False
    elif event.key==pygame.K_LEFT:
        self.ship.moving_left=False
def _fire_bullet(self):
    """create a new bullet and add it to the bullet group"""
    if len(self.bullets) < (self.settings.bullets_allowed):
        new_bullet=Bullet(self)
        self.bullets.add(new_bullet)
def _update_bullets(self):
    """Update position of bullets and get rid of old bullets."""
    # Update bullet positions.
    self.bullets.update()
    #getting rid of old fired bullets
    for bullet in self.bullets.copy():
        if bullet.rect.bottom <= 0:
            self.bullets.remove(bullet)
def _update_aliens(self):
    """initialise right movement of aliens to right"""
    self.aliens.update()
        
def _create_fleet(self):
    """create the fleet of aliens"""
    #creating an alien and find the the number of aliens in a row.
    #spacing between each alien is one alien width.
    alien=Alien(self)
    alien_width, alien_height= alien.rect.size
    alien_width=alien.rect.width
    available_space_x=self.settings.screen_width-(2*alien_width)
    number_aliens_x=available_space_x//(2*alien_width)
    #determine number of rows that fit on the screen
    ship_height=self.ship.rect.height
    available_space_y = (self.settings.screen_height - (3 * alien_height) - ship_height)
    number_rows = available_space_y // (2 * alien_height)
    #create full fleet of aliens.
    for row_number in range(number_rows):
        for alien_number in range(number_aliens_x):
            self._create_alien(alien_number, row_number)
def _create_alien(self,alien_number, row_number):
    #create an alien and place it in the row.
    alien=Alien(self)
    alien_width, alien_height= alien.rect.size
    alien_width=alien.rect.width
    alien.x=alien_width + 2 * alien_width * alien_number
    alien.rect.x=alien.x
    alien.rect.y=alien.rect.height + 2 * alien.rect.height * row_number
    self.aliens.add(alien)
def _check_fleet_edges(self):
    """respond appropriately if any aliens have reached the edge"""
    for alien in self.aliens.sprites():
        if alien.check_edges():
            self._change_fleet_direction()
            break
def _change_fleet_direction(self):
    """drop entire fleet and change direction"""
    for alien in self.aliens.sprites():
        alien.rect.y += self.settings.fleet_drop_speed
    self.settings.fleet_direction *= -1
def _update_screen(self):
    """update images on the screen and flip to the new screen."""
    self.screen.fill(self.settings.bg_color)
    self.ship.blitme()
    for bullet in self.bullets.sprites():
        bullet.draw_bullet()
    self.aliens.draw(self.screen)
        
    #make the most recently drawn screen visible,
    pygame.display.flip()
if __name__=='__main__':
    #make a game instance and run the game.
    ai=AlienInvasion()
    ai.run_game()
```

ship.py

  ```
  import pygame
class Ship:
"""a class to manage the ship"""
def __init__(self,ai_game):
    """initialize the ship and set its starting position."""
    self.screen=ai_game.screen
    self.settings=ai_game.settings
    self.screen_rect=ai_game.screen.get_rect()
    #load the ship image and its rect.
    self.image=pygame.image.load('images/ship.bmp')
    self.rect=self.image.get_rect()
    #start each new ship at the bottom center of the screen.
    self.rect.midbottom=self.screen_rect.midbottom
    #store a decimal value for ship's horizontal position.
    self.x=float(self.rect.x)
    #movement_flags
    self.moving_right=False
    self.moving_left=False
def update(self):
    #update ship's position based on movement flags
    #update the ship's x value, not the rect.
    if self.moving_right and self.rect.right < self.screen_rect.right:
        self.x += self.settings.ship_speed
    if self.moving_left and self.rect.left > 0:
        self.x -= self.settings.ship_speed
    #update rect object from self.x
    self.rect.x=self.x
def blitme(self):
    """draw the ship st its current location."""
    self.screen.blit(self.image,self.rect)

alien.py

import pygame
from settings import settings
from pygame.sprite import Sprite
class Alien(Sprite):
    """A class to represent a single alien in the fleet."""
    def __init__(self,ai_game):
        """initialise alien and set its starting position"""
        super().__init__()
        self.screen=ai_game.screen
        self.settings=ai_game.settings
        #load alien image and set its rect attribute.
        self.image=pygame.image.load('images/corona.bmp')
        self.rect=self.image.get_rect()
        #start the alien on top left corner of the screen.
        self.rect.x=self.rect.width
        self.rect.y=self.rect.height
        #store exact rect position of the alien.
        self.x=float(self.rect.x)
    def check_edges(self):
        """Return True if alien is at edge of screen."""
        screen_rect = self.screen.get_rect()
        if self.rect.right >= screen_rect.right or self.rect.left<=0:
            return True
    def update(self):
        """make the aliens move right"""
        self.x += (self.settings.alien_speed * self.settings.fleet_direction)
        self.rect.x=self.x

settings.py

class settings:
    """a class to store all settings for alien invasion."""
    def __init__(self):
        """initialise game's settings"""
        #screen settings
        self.screen_width=1250
        self.screen_height=650
        self.bg_color=(103,113,214)
        #bullet settings
        self.bullets_allowed=10
        self.bullet_speed=8
        self.bullet_height=15
        self.bullet_width=3
        self.bullet_color=(255,0,0)
        #ship settings
        self.ship_speed=1.5
        #alien settings
        self.alien_speed=1.0
        self.fleet_drop_speed=15
        # (1) represents fleet direction right and (-1) represents left direction
        self.fleet_direction=1

bullets.py

import pygame
from pygame.sprite import Sprite
class Bullet(Sprite):
    """A class to manage bullets fired from the ship"""
    def __init__(self,ai_game):
        """create a bullet object at ship's current position"""
        super().__init__()
        self.screen=ai_game.screen
        self.settings=ai_game.settings
        self.color=self.settings.bullet_color
        #create a bullet rect at (0,0) and then set correct position
        self.rect=pygame.Rect(0,0,self.settings.bullet_width,self.settings.bullet_height)
        self.rect.midtop=ai_game.ship.rect.midtop
        #store bullet's position as a decimal value
        self.y=float(self.rect.y)
    def update(self):
        """move the bullet up the screen"""
        #update decimal position of the bullet
        self.y -= self.settings.bullet_speed
        #update the rect position
        self.rect.y=self.y
    def draw_bullet(self):
        """draw the bullet to the screen"""
        pygame.draw.rect(self.screen,self.color,self.rect)
0

这是一个相当简单的错误:

def run_game(self):
    """start main loop for the game"""
    while True:
        self._check_events()
        self.ship.update()
        self._update_bullets()
        self._create_fleet()     # <<-- HERE
        self._update_screen()
        self._update_aliens()
        print( "Aliens: " + str( len( self.aliens ) ) )

每一个屏幕绘画,它都在调用_create_fleet(),这将为self.aliensSprite Group 添加一堆更多外星人。

所以你没有看到原来的外星人移动有趣,但新的外星人被添加,和位图一起抚摸(这是一个技术术语;)

如果你包括print()我上面添加到你的主循环,它真的很清楚:

user@linux# python3 ./bad_aliens.py 
pygame 2.0.1 (SDL 2.0.14, Python 3.6.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
Aliens: 144
Aliens: 288
Aliens: 432
Aliens: 576
...

几秒钟后有 10000 个外星人。哎呀。

可能你想要的是这样的:

def run_game(self):
    """start main loop for the game"""
    self._create_fleet()                  # Make some aliens (just once)
    while True:
        self._check_events()
        self.ship.update()
        self._update_bullets()
        self._update_screen()
        self._update_aliens()

本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处

(37)
Python可变参数传递:Go可变函数参数传递(variadic function golang)
上一篇
Try组合:List[Try[T]]toTry[List[T]] inScala
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(18条)