Actually i am building a game in pygame called Alien invasion in which a ship fires bullets to aliens. I am at early stage of the game but i have a problem here .My game was working properly when i did not add continuous movement but now it is not moving as i expected!
I HAVE THREE FILES OF PYTHON:
1: aline_invasion.py
import pygame
import sys
from settings import Settings
from ship import Ship
class AlienInvasion:
"""Overall class to control game assets and behaviour"""
def __init__(self):
pygame.init()
self.setting = Settings()
self.screen = pygame.display.set_mode((self.setting.screen_width, self.setting.screen_height))
self.title = self.setting.game_title
self.ship = Ship(self)
def run_game(self):
while True:
self._check_events()
self.ship.update()
self._update_screen()
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.type == pygame.K_UP:
if event.key == pygame.K_RIGHT:
self.ship.moving_right = False
elif event.key == pygame.K_LEFT:
self.ship.moving_left = False
def _update_screen(self):
self.screen.fill(self.setting.bg_color)
self.ship.blit_me()
pygame.display.flip()
if __name__ == '__main__':
ai = AlienInvasion()
ai.run_game()
2: settings.py
import pygame
class Settings:
def __init__(self):
self.screen_width = 900
self.screen_height = 600
self.bg_color = (230, 230, 230)
self.game_title = pygame.display.set_caption('Alien Invasion')
3: ship.py
import pygame
class Ship:
def __init__(self, ai_game):
self.screen = ai_game.screen
self.screen_rect = self.screen.get_rect()
self.moving_right = False
self.moving_left = False
# Load the ship image and get its rect
self.image = pygame.image.load('images/ship.png')
self.rect = self.image.get_rect()
# Start each new ship at the bottom center of the screen.
self.rect.midbottom = self.screen_rect.midbottom
def update(self):
if self.moving_right:
self.rect.x += 1
if self.moving_left:
self.rect.x -= 1
def blit_me(self):
# Draw the ship at its current location
self.screen.blit(self.image, self.rect)