嘿,对不起,打扰您了,但是为了使它正常工作,我现在浪费了很多时间。
代码工作正常,但是在发射后,弹丸保持方向不变,因此我尝试为每个子弹分配自己的dir值,并使用shot功能将子弹移动到弹丸类中。但我不断收到错误消息:
回溯(最近一次通话最近):文件“ 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:类型对象'projectile'没有属性'dir'
我认为很显然我是编码新手,所以我非常感谢您的帮助。
将get_input函数中的projectile.dir更改为bullet.dir,仅更改为dir。 将方向放在方括号中。在get_input函数外部分配的方向。在初始化函数之前在弹丸类中分配了字母
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()
答案 0 :(得分:0)
DialogFragment
现在是instance attribute,因此类属性ViewModel
不再存在。
在全局名称空间中创建变量.dir
。使用global
statement写入函数projectile.dir
中的变量,并使用该变量设置构造新的current_dir
对象时的方向:
get_input
旁注projectile
是比较等于运算符。要设置current_dir = 'N'
def get_input(ev):
global current_dir
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
player.y -= player.speed
current_dir = 'N'
if keys[pygame.K_a]:
player.x -= player.speed
current_dir = 'W'
if keys[pygame.K_s]:
player.y += player.speed
current_dir = 'S'
if keys[pygame.K_d]:
player.x += player.speed
current_dir = 'E'
for event in ev:
if event.type == pygame.MOUSEBUTTONDOWN:
px, py = round(player.x + player.width//2), round(player.y + player.height//2)
new_prj = projectile(px, py, current_dir)
bullets.append(new_prj)
,您必须使用赋值运算符==
。
在主循环中避免多次调用pygame.event.get()
。一次获取事件,并将事件列表传递给函数current_dir
和=
:
update