python-3.x – PyGame桨板不动

关键事件在控制台上正常注册.此外,我的桨显示,这表明我从另一个文件调用的paddle类工作.但是,当按下左箭头键或右箭头键时,我希望我的拨片顺利移动,这样用户就不必反复点击.但是,使用我当前的代码,拨片根本不会移动.我已经尝试改变if / else语句的位置,改变位置无济于事.我在这做错了什么?

主要游戏:

import pygame
from pygame.locals import *

from Config import Config 
from Paddle import Paddle

pygame.init()

#--Display settings
pygame.display.set_caption(Config['game']['caption'])
game_display = pygame.display.set_mode((Config['game']['display_width'], 
Config['game']['display_height']))
clock = pygame.time.Clock()
paddle= Paddle(game_display)

x_change = 0
pressed_left = False
pressed_right = False

def event_handler():
for event in pygame.event.get():
    print (event)
    if (event.type == QUIT) or (event.type == KEYDOWN and event.key == 
K_ESCAPE):
        pygame.quit()
        quit()

    #To move the paddle to the left and right
    if event.type == KEYDOWN:
        if event.key == K_LEFT:
            pressed_left = True  
        elif event.key== K_RIGHT:
            pressed_right = True

    #If the key is up
    if event.type == KEYUP:
        if event.key == K_LEFT:
            pressed_left = False
            x_change = 0
        elif event.key == K_RIGHT:
            pressed_right = False 
            x_change = 0

#--This changes the position
if pressed_left:
    x_change = -5
if pressed_right:
    x_change = 5

while True:
    event_handler()
    game_display.fill(Config['colors']['white'])
    paddle.draw()
    paddle.movement(x_change)

    pygame.display.update()
    clock.tick(Config['game']['fps'])

从我的paddle.py包含Paddle类:

import pygame
from pygame.locals import *

from Config import Config

class Paddle:
    def __init__(self, game_display):
        self.x = (Config['game']['display_width'] * 0.45)
        self.y = (Config['game']['display_height'] * 0.92)
        self.game_display=game_display


    def draw(self):
        pygame.draw.rect(self.game_display, Config['colors']['red'], 
[self.x, self.y, 40, 25])

    def movement(self, x_change):
        self.x += x_change

最佳答案 让我们看一个更简单的例子.尝试运行此程序.

pressed_left = False
def event_handler():
    pressed_left = True

event_handler()

print(pressed_left)

虽然您希望程序打印为True,但它会打印False.这是因为变量作用域在python中的工作方式.当您尝试修改未在该函数本身中定义的函数中的变量时,python会定义一个新变量,而不是查找全局变量.
因此,event_handler()中的pressed_left = True行只创建一个新的pressed_left变量,该变量仅存在于event_handler函数中,而不修改全局变量.

要解决此问题,您需要在函数中将变量声明为全局变量.尝试运行此程序.

pressed_left = False
def event_handler():
    global pressed_left
    pressed_left = True

event_handler()

print(pressed_left)
点赞