【发布时间】:2019-07-18 16:49:09
【问题描述】:
大家好,很抱歉打扰您,但我现在浪费了几个小时来修补以使其正常工作。
代码运行良好,但射弹在发射后不断改变方向,所以我尝试为每个子弹分配自己的 dir 值并将移动子弹的射击函数放入射弹类。但我不断收到错误消息:
Traceback(最近一次调用最后):文件“PycharmProjects/Game/Pygame.py”,第 90 行,在 update() 文件“PycharmProjects/Game/Pygame.py”,第 73 行,在 update get_input() 文件中“ PycharmProjects/Game/Pygame.py",第 55 行,在 get_input projectile.dir == {'N'} AttributeError: type object 'projectile' has no attribute 'dir'
我认为很明显我是编码新手,因此非常感谢您的帮助。
将 get_input 函数中的 projectile.dir 更改为 bullet.dir 和只是 dir。 将方向放在括号中。在 get_input 函数之外分配方向。在初始化函数之前在类 projectile 中分配了字母
class player():
x = WIDTH / 2
y = HEIGHT / 2
width = 50
height = 50
speed = 1
def draw(self):
pygame.draw.rect(win, (0, 0, 255), (self.x, self.y, self.width, self.height))
class projectile():
radius = 10
speed = 8
def __init__(self, x, y, dir={}):
self.x = x
self.y = y
self.dir = dir
def shot(self):
for bullet in bullets:
if self.dir == 'N':
print('N')
self.y -= 1
if self.dir == 'W':
print('W')
self.x -= 1
if self.dir == 'S':
print('S')
self.y += 1
if self.dir == 'E':
print('E')
self.x += 1
def draw(self):
pygame.draw.circle(win, (255, 0, 0), (self.x, self.y), self.radius)
def get_input():
keys = pygame.key.get_pressed()
ev = pygame.event.get()
if keys[pygame.K_w]:
player.y -= player.speed
projectile.dir == 'N'
if keys[pygame.K_a]:
player.x -= player.speed
projectile.dir == 'W'
if keys[pygame.K_s]:
player.y += player.speed
projectile.dir == 'S'
if keys[pygame.K_d]:
player.x += player.speed
projectile.dir == 'E'
for event in ev:
if event.type == pygame.MOUSEBUTTONDOWN:
bullets.append(projectile(round(player.x + player.width//2), round(player.y + player.height//2), dir))
def update():
clock.tick(300)
win.fill ((0, 0, 0))
get_input()
player.draw()
for bullet in bullets:
bullet.draw()
bullet.shot()
pygame.display.update()
running = True
player = player()
bullets = []
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
update()
#pygame.quit()
【问题讨论】:
-
这里是错误消息:Traceback(最近一次调用最后一次):文件“PycharmProjects/Game/Pygame.py”,第 90 行,在
update() 文件“PycharmProjects/Game/Pygame .py”,第 73 行,更新 get_input() 文件“PycharmProjects/Game/Pygame.py”,第 55 行,get_input projectile.dir == {'N'} AttributeError: type object 'projectile' has no attribute 'dir '
标签: python python-3.x class object pygame