PythonPyGame重构。。。将代码包装到方法中
我在一个方向键的主循环中有以下重复代码,PythonPyGame重构。。。将代码包装到方法中,python,duplicates,pygame,refactoring,Python,Duplicates,Pygame,Refactoring,我在一个方向键的主循环中有以下重复代码,WASD在一个pygame应用程序中,我正在尝试重新考虑。我很难找到最好的方法。我创建了一个玩家类p游戏类g和一个世界级w的实例 理想情况下,我想在游戏类中创建一个名为updatePositions的方法。我遇到的主要问题是因为我必须-=或+=并且我发现如果不为一个单独的WASD键编写一个完整的if语句,我很难做到这一点。一定有更好的办法 if event.key == pygame.K_w: p.fov.y -= g.p
WASD
在一个pygame应用程序中,我正在尝试重新考虑。我很难找到最好的方法。我创建了一个玩家类p
游戏类g
和一个世界级w
的实例
理想情况下,我想在游戏
类中创建一个名为updatePositions
的方法。我遇到的主要问题是因为我必须-=或+=并且我发现如果不为一个单独的WASD键编写一个完整的if语句,我很难做到这一点。一定有更好的办法
if event.key == pygame.K_w:
p.fov.y -= g.pixelUpdate
for ent in w.entityList:
ent.rect.y += g.pixelUpdate
ent.collisionRect.y += g.pixelUpdate
for ent in w.ents_in_fov:
if p.collision(ent):
p.collided = True
for ent in w.entityList:
ent.rect.y -= g.pixelUpdate
ent.collisionRect.y -= g.pixelUpdate
p.fov.y += g.pixelUpdate
elif event.key == pygame.K_d:
p.fov.x += g.pixelUpdate
for ent in w.entityList:
ent.rect.x -= g.pixelUpdate
ent.collisionRect.x -= g.pixelUpdate
for ent in w.ents_in_fov:
if p.collision(ent):
p.collided = True
for ent in w.entityList:
ent.rect.x += g.pixelUpdate
ent.collisionRect.x += g.pixelUpdate
p.fov.x -= g.pixelUpdate
elif event.key == pygame.K_s:
p.fov.y += g.pixelUpdate
for ent in w.entityList:
ent.rect.y -= g.pixelUpdate
ent.collisionRect.y -= g.pixelUpdate
for ent in w.ents_in_fov:
if p.collision(ent):
p.collided = True
for ent in w.entityList:
ent.rect.y += g.pixelUpdate
ent.collisionRect.y += g.pixelUpdate
p.fov.y -= g.pixelUpdate
elif event.key == pygame.K_a:
p.fov.x -= g.pixelUpdate
for ent in w.entityList:
ent.rect.x += g.pixelUpdate
ent.collisionRect.x += g.pixelUpdate
for ent in w.ents_in_fov:
if p.collision(ent):
p.collided = True
for ent in w.entityList:
ent.rect.x -= g.pixelUpdate
ent.collisionRect.x -= g.pixelUpdate
p.fov.x += g.pixelUpdate
提示1:您可以使用
a+=-b
提示2:您可以使用值0
p.fov.x += 0
p.fov.y += g.pixelUpdate
p.fov.x += g.pixelUpdate
p.fov.y += 0
因此,您可以创建updatePositions(x,y)
并按如下方式执行
if event.key == pygame.K_w:
updatePositions(0, -g.pixelUpdate)
elif event.key == pygame.K_s
updatePositions(0, g.pixelUpdate)
elif event.key == pygame.K_d:
updatePositions(g.pixelUpdate, 0)
elif event.key == pygame.K_a:
updatePositions(-g.pixelUpdate, 0)
编辑:类似以下内容:
def updatePositions(x, y):
p.fov.x += x
p.fov.y += y
for ent in w.entityList:
ent.rect.x -= x
ent.rect.y -= y
ent.collisionRect.x -= x
ent.collisionRect.x -= y
for ent in w.ents_in_fov:
if p.collision(ent):
p.collided = True
for ent in w.entityList:
ent.rect.x += x
ent.rect.y += y
ent.collisionRect.x += x
ent.collisionRect.y += y
p.fov.x -= x
p.fov.y -= y
顺便说一句:可能需要
更新位置(x,y,p,w)
才能访问p
和w
来帮助一个noob,看看那些可怕的重复代码提示:你可以使用a+=-b
而不是a+=-b
,这样你就可以用a+=x
创建一个函数,然后用x=b
或x=-b
执行它。这很完美,这正是我需要的。我不知道我能做的x+=-1
和x-=1
一样——很漂亮。它在我的脑海里点亮了一盏巨大的灯。非常感谢。