为什么控制键盘不起作用?左右鼠标

时间:2018-07-01 16:11:12

标签: python keyboard pygame controls mouse

文件Alien_invasion.py是应用程序的主文件。为什么控制鼠标不起作用?如何在此示例中制作控制键盘并在左右位置附带控件?

其中是控制鼠标/键盘的文件

文件: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

船舶设置

文件: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

运行应用的主文件

文件: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()

1 个答案:

答案 0 :(得分:1)

因为您仅调用一次check_events函数;那么您进入while True:循环,就再也不需要检查键盘事件了。

真正帮助您的是学习调试技术。可以尝试使用调试器,也可以使用简单的print语句来判断您的程序在做什么。