我正在学习python 我创建了用于玩家移动的代码,当它不在课堂上时可以使用,但是我在课堂上需要它。 当我按W或S时,播放器仅按vel = 5移动一次,然后返回到其原始坐标。如何解决?
right = False
left = False
class player:
def __init__(self, x, y, vel = 5, walkCount = 0):
self.x = x
self.y = y
self.vel = vel
self.walkCount = walkCount
def update(self):
if self.walkCount + 1 >= 40:
self.walkCount = 0
if right:
screen.blit(charRun[walkCount//5],(self.x, self.y))
self.walkCount += 1
elif left:
screen.blit(charBack[walkCount//5],(self.x, self.y))
self.walkCount += 1
else:
screen.blit(char,(self.x, self.y))
pygame.display.update()
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.x += self.vel
right = True
left = False
elif keys[pygame.K_s]:
self.x -= self.vel
left = True
right = False
else:
right = False
left = False
self.walkCount = 0
def redrawGameWindow():
screen.blit(bg, (0, 0))
screen.blit(car, (800,500))
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
redrawGameWindow()
b = player(500,500)
b.move()
b.update()
答案 0 :(得分:0)
按照@jasonharper的建议,您只需在开始时创建一次播放器,然后在类中创建左右变量即可。
class player:
def __init__(self, x, y, vel = 5, walkCount = 0):
self.x = x
self.y = y
self.vel = vel
self.walkCount = walkCount
self.right = False
self.left = False
def update(self):
if self.walkCount + 1 >= 40:
self.walkCount = 0
if right:
screen.blit(charRun[walkCount//5],(self.x, self.y))
self.walkCount += 1
elif left:
screen.blit(charBack[walkCount//5],(self.x, self.y))
self.walkCount += 1
else:
screen.blit(char,(self.x, self.y))
pygame.display.update()
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
self.x += self.vel
self.right = True
self.left = False
elif keys[pygame.K_s]:
self.x -= self.vel
self.left = True
self.right = False
else:
self.right = False
self.left = False
self.walkCount = 0
def redrawGameWindow():
screen.blit(bg, (0, 0))
screen.blit(car, (800,500))
run = True
b = player(500,500)
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
redrawGameWindow()
b.move()
b.update()
答案 1 :(得分:0)
首先,要检查出什么问题,应该发布大多数代码,以便我们可以尝试对其进行测试和调试。 其次,编程中的类确实很有用,但是您不应做任何对代码没有意义的事情。类在那里可以帮助您创建许多对象,但也可以维护代码的稳定性。
因此,您的所有代码都应该有意义。例如,在您的代码中,您让播放器更新了显示内容。 display.update方法在您的while循环中会更好,因为无论何时更新屏幕,播放器都不应控制。想象一下,以后您添加内容,但是您的代码不起作用,因为显示内容没有更新...
无论如何,让我们回到代码。您可以在此处看到您在while循环中创建对象。因此,每次执行循环时,您都会使用默认值创建一个新对象:
b = player(500,500)
因此,此函数每执行一次周期:
def __init__(self, x, y, vel = 5, walkCount = 0):
self.x = x
self.y = y
self.vel = vel
self.walkCount = walkCount
所以x和y保持在500。