Python全系列 教程
3567个小节阅读:5929k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
坦克类中添加速度属性,实现我方坦克移动。
xxxxxxxxxx
class Tank:
'''
坦克类
'''
def __init__(self,left:int,top:int) -> None:
# 设置我方坦克的图片资源
self.images = {
'U':pygame.image.load('./img/p1tankU.gif'),
'D':pygame.image.load('./img/p1tankD.gif'),
'L':pygame.image.load('./img/p1tankL.gif'),
'R':pygame.image.load('./img/p1tankR.gif'),
}
# 设置我方坦克的方向
self.direction = 'L'
# 获取图片信息
self.image = self.images.get(self.direction)
# 获取图片的矩形
self.rect = self.image.get_rect()
# 设置我方坦克位置
self.rect.left = left
self.rect.top = top
# 设置移动速度
self.speed = 10
def display_tank(self) -> None:
'''
显示坦克
'''
# 获取最新坦克的朝向位置图片
self.image = self.images.get(self.direction)
MainGame.window.blit(self.image,self.rect)
def move(self) -> None:
'''
坦克的移动
'''
if self.direction == "L":
# 判断坦克的位置是否已左边界
if self.rect.left > 0:
# 修改坦克的位置 离左边的距离 - 操作
self.rect.left = self.rect.left - self.speed
elif self.direction == "R":
# 判断坦克的位置是否已右边界
if self.rect.left + self.rect.width < SCREEN_WIDTH:
# 修改坦克的位置 离左边的距离 + 操作
self.rect.left = self.rect.left + self.speed
elif self.direction == "U":
# 判断坦克的位置是否已上边界
if self.rect.top > 0:
# 修改坦克的位置 离上边的距离 - 操作
self.rect.top = self.rect.top - self.speed
elif self.direction == "D":
# 判断坦克的位置是否已下边界
if self.rect.top + self.rect.height < SCREEN_HEIGHT:
# 修改坦克的位置 离上边的距离 + 操作
self.rect.top = self.rect.top + self.speed
在上面方法中,按一下坦克移动一下,想按下键时候,坦克一直移动,弹起坦克停止移动。
在坦克类中添加移动开关属性,按下上、下、左、右四个方向键修改坦克的方向及开关状态stop = False。松开方向键,更改移动开关状态stop = True。
xxxxxxxxxx
#获取程序期间所有事件(鼠标事件,键盘事件)
def getEvent(self):
#1.获取所有事件
eventList = pygame.event.get()
#2.对事件进行判断处理(1、点击关闭按钮 2、按下键盘上的某个按键)
for event in eventList:
#判断event.type 是否QUIT,如果是退出的话,直接调用程序结束方法
if event.type == pygame.QUIT:
self.endGame()
#判断事件类型是否为按键按下,如果是,继续判断按键是哪一个按键,来进行对应的处理
if event.type == pygame.KEYDOWN:
#具体是哪一个按键的处理
if event.key == pygame.K_LEFT:
print("坦克向左调头,移动")
#修改坦克方向
MainGame.TANK_P1.direction = 'L'
MainGame.TANK_P1.stop = False
elif event.key == pygame.K_RIGHT:
print("坦克向右调头,移动")
# 修改坦克方向
MainGame.TANK_P1.direction = 'R'
MainGame.TANK_P1.stop = False
elif event.key == pygame.K_UP:
print("坦克向上调头,移动")
# 修改坦克方向
MainGame.TANK_P1.direction = 'U'
MainGame.TANK_P1.stop = False
elif event.key == pygame.K_DOWN:
print("坦克向下掉头,移动")
# 修改坦克方向
MainGame.TANK_P1.direction = 'D'
MainGame.TANK_P1.stop = False
elif event.key == pygame.K_SPACE:
print("发射子弹")
#结束游戏方法
if event.type == pygame.KEYUP:
#松开的如果是方向键,才更改移动开关状态
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT or event.key == pygame.K_UP or event.key == pygame.K_DOWN:
# 修改坦克的移动状态
MainGame.TANK_P1.stop = True