python整体向右移动_【python3小白上路系列】左右移动

为了保证文章的原创性,我决定用自己理解的语言开始后面的学习笔记。

1.4.3 左右移动

之前我们添加了飞船向右移动功能,同时对持续移动做了更新和改进。下面我们该添加向左移动飞船的功能了。需要修改ship类和函数check_events()。

先来修改ship类:

import pygame

class Ship():

def __init__(self,screen):

#初始化飞船并设置其初始位置

self.screen = screen

# 加载飞船图像并获取其外接矩形

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

def update(self):

#根据移动标志调整飞船的位置

if self.moving_right:

self.rect.centerx += 1

if self.moving_left:

self.rect.centerx -= 1

def blitme(self):

# 在指定位置绘制飞船

self.screen.blit(self.image, self.rect)

这里首先要在init函数中增加向左移动飞船的标志,同时初始化为False。然后修改update函数,当标志为left时,飞船的位置向左移动1。接下来仿照向右移动的功能,我们要修改game_function中的check_events()。

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

def update_screen(ai_settings,screen,ship):

#每次循环时都重绘屏幕

screen.fill(ai_settings.bg_color)

# 屏幕上绘制飞船#

ship.blitme()

#让最近绘制的屏幕可见#

pygame.display.flip()

下节预告:优化移动功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值