《python编程从入门到实践》十二章12.6

#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_LEFT:
                ship.moving_left = True
            elif event.key == pygame.K_RIGHT:
                ship.moving_right = True

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

def update_screen(screen, ai_settings, ship):
    screen.fill(ai_settings.bg_color)
    ship.update()
    ship.blitme()
    pygame.display.flip()
#settings.py
import pygame

class Settings():
    def __init__(self):
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (230,230,230)
#ship.py
import pygame

class Ship():
    """创建ship类"""
    def __init__(self, screen):
        self.screen = screen
        self.image = pygame.image.load("images/ship.bmp")
        self.rect = self.image.get_rect()
        self.screen_rect = self.screen.get_rect()

        #设置飞船的位置
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        #左右移动标志量
        self.moving_left = False
        self.moving_right = False

    def update(self):
        if self.moving_left:
            self.rect.centerx -= 1
        if self.moving_right:
            self.rect.centerx += 1

    def blitme(self):
        self.screen.blit(self.image, self.rect)
#主程序
import sys

import pygame

from settings import Settings
from ship import Ship

import game_functions as gf

def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width,ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    ship = Ship(screen)

    while True:
        gf.check_events(ship)               
        gf.update_screen(screen, ai_settings, ship)
run_game()

今天敲了《python编程从入门到实践》的第十二章外星人入侵,只敲到12.6,但是有一个疑问,为什么代码片game_functions.py中的check_events函数判断时候用的是,if-elif,按照自己的理解这里应该是两个if呀,但是按照书中的方法实现的又没有错。很迷惑。

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_LEFT:
                ship.moving_left = True
            elif event.key == pygame.K_RIGHT:
                ship.moving_right = True

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

敲了三天这些代码,发现多敲果然非常有好处,前面看到这些代码是懵逼的,但是现在看到它们感到非常的熟悉,以后一定要多敲代码!!!!

你可能感兴趣的:(python学习)