Hubert95
Hubert95

Reputation: 31

Why control keyboard doesn't work? Right and left mouse

The file alien_invasion.py is the main file of the app. Why control mouse doesn't work? How make control keyboard to this example and control ship with left and right site?

file in which is control mouse/keyboard

file: game_functions.py

import sys
import pygame

def check_events(ship):


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                ship.moving_right = True
            elif event.key == pygame.K_LEFT:
                 ship.moving_left = True

        elif event.type == pygame.KEYUP :
            if event.key == pygame.K_RIGHT:
                ship.moving_right = False
            elif event.key == pygame.K_LEFT:
                ship.moving_left = False

settings for ship

file: ship.py

import pygame

class Ship():
    def __init__(self, ai_settings, screen):
        self.screen = screen
        self.ai_settings = ai_settings

        self.image = pygame.image.load('images/ship.png')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        self.moving_right = False
        self.moving_left = False

        self.center = float(self.rect.centerx)


    def blitme(self):
        self.screen.blit(self.image, self.rect)

    def update(self):


        if self.moving_right and self.rect.right < self.screen_rect.right:
            self.center += self.ai_settings.ship_speed_factor
        if self.moving_left and self.rect.left > 0:
            self.center -= self.ai_settings.ship_speed_factor

        self.rect.centerx = self.center

the main file which run app

file: alien_invasion.py

import sys
import pygame
from settings import Settings
from ship import Ship
import game_functions as gf

def run_game():
    pygame.init()
    pygame.display.set_caption("Inwazja obcych")
    ai_settings = Settings()
    screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height))
    ship = Ship(ai_settings, screen)
    gf.update_screen(ai_settings, screen, ship)
    gf.check_events(ship)
    ship.update()

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        screen.fill(ai_settings.bg_color)
        ship.blitme()
        pygame.display.flip()

run_game()

Upvotes: 0

Views: 58

Answers (1)

sloth
sloth

Reputation: 101122

Because you call the check_events function only once; then you enter the while True: loop and never check for keyboard events again.

What would really help you is learning debugging techniques. Either try using a debugger or use simple print statements to be able to tell what your program is doing.

Upvotes: 1

Related Questions