无法在pygame中获得左右移动船舶的“功能”

问题描述

python 和 pygame 的新手。我试图让船连续向左或向右移动,我通过创建一个类“move_ship”并将 self.arguments 传递为 false 来做到这一点。然后创建了一个函数,当 self.arguments 为 True 并增加或减少船的 x 位置值时,该函数在其中起作用。然后用变量“ship_moving”调用类。 ...创建了一个事件,将 self.argument 设置为 true,最后调用类中的函数来移动船:-

class move_ship():
   def __init__(self):
     self.moving_left=False
     self.moving_right=False
   def moving(self):
     if self.moving_left:
        ship_rect.centerx-=1
     if self.moving_right:
        ship_rect.centerx+=1

ship_moving=move_ship()

def run_game:
    pygame.init()
    while True:
       for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type ==pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    ship_moving.moving_right=True
                elif event.key == pygame.K_LEFT:
                    ship_moving.moving_left=True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    ship_moving.moving_right=False
                elif event.key == pygame.K_LEFT:
                    ship_moving.moving_left=False
    
    ship_moving.moving()

它工作得很好,但我想知道为什么当我尝试同样的事情但只有功能时它不起作用。

moving_right=False
moving_left= False
def move_ship():
  if moving_left:
     ship_rect.centerx-=1
  if moving_right:
     ship_rect.centerx+=1



def run_game:
    pygame.init()
    while True:
       for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type ==pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    moving_right=True
                elif event.key == pygame.K_LEFT:
                    moving_left=True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    moving_right=False
                elif event.key == pygame.K_LEFT:
                    moving_left=False
    
    move_ship()

解决方法

如果要在函数内的全局命名空间中设置变量,则必须使用 global statement

def run_game():
    global moving_right,moving_left 

    pygame.init()
    while True:
       for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type ==pygame.KEYDOWN:
                if event.key == pygame.K_RIGHT:
                    moving_right=True
                elif event.key == pygame.K_LEFT:
                    moving_left=True

            elif event.type == pygame.KEYUP:
                if event.key == pygame.K_RIGHT:
                    moving_right=False
                elif event.key == pygame.K_LEFT:
                    moving_left=False

如果不指定moveing_rightmoveing_left解释为全局,则在run_game函数的作用域内只设置同名的局部变量,但全局变量永远不会改变。